7

I am trying to figure out how to send a file and paramaters within the same XMLHttpRequest. Is this possible?

Obviously I can do xhr.send(file+params) or xhr.(file,params). And I don't think I can set two different request headers to do this...

xhr.setRequestHead('X_FILENAME', file.name)
xhr.send(file);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);

Is there some way to send the params without having to use GET, or a secondary xhr request?

4

2 回答 2

12

如果您依赖支持的浏览器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);

然后,在您的服务器端,您可以使用以下代码(PHP)访问您的变量:

<?
  $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"])

于 2013-11-08T03:45:44.027 回答
6

有什么方法可以发送参数而无需使用 GET 或辅助 xhr 请求?

是的,您可以将它们编码到 URL 中(就像GET),即使您正在执行POST. 例如:

xhr.open(yourUrl + "?foo=" + encodeURIComponent(foo) + "&bar=" + encodeURIComponent(bar));
// ...
xhr.send(file);

我在上面假设您必须知道关于通过 XHR 发送文件的一些我不知道的事情。:-)


假设这file是文件的实际内容,通过File API读取,那么它不只是另一个参数吗?所以:

xhr.send(
    "filedata=" + encodeURIComponent(file) +
    "&foo=" + encodeURIComponent(foo) +
    "&bar=" + encodeURIComponent(bar)
);
于 2013-03-05T07:47:19.177 回答