我试图弄清楚如何在同一
XMLHttpRequest中发送文件和参数.这可能吗?
显然我可以做xhr.send(文件参数)或xhr.(文件,参数).而且我认为我不能设置两个不同的请求标头来执行此操作…
xhr.setRequestHead('X_FILENAME',file.name) xhr.send(file); xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xhr.send(params);
有没有办法发送params而不必使用GET或次要xhr请求?
解决方法
如果您依赖支持FormData的浏览器,您可以使用下面的代码(JavaScript):
var formData = new FormData(); formData.append('param1','myParam'); formData.append('param2',12345); formData.append('uploadDir','public-data'); formData.append('myfile',file); xhr.send(formData);
<? $param1 = $_POST['param1']; //myParam $param2 = $_POST['param2']; //12345 $uploaddir = $_POST['uploadDir']; //public-data $fileName = $_FILES['myfile']['name']; $fileZise = $_FILES['myfile']['size']; $uploaddir = getcwd().DIRECTORY_SEPARATOR.$uploaddir.DIRECTORY_SEPARATOR; $uploadfile = $uploaddir.basename($fileName); move_uploaded_file($_FILES['file']['tmp_name'],$uploadfile); echo $fileName.' ['.$fileZise.'] was uploaded successfully!'; ?>
要获取$_FILES [‘myfile’]的所有参数,请使用var_dump($_ FILES [“myfile”])