本文介绍了HTML5 文件 API readAsBinaryString 读取的文件比磁盘上的文件大得多的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

完整代码位于 https://gist.github.com/992562.

我正在使用 HTML 文件 API 并通过 XHR post 拖/放将文件上传到 PHP 脚本.从程序上看,一切似乎都正常,但是当我尝试打开上传的文件时,任何非文本文件都比源文件大得多,并且无法打开.它显然与源磁盘上的数据不同.但是,文本文件完全一样,打开也很好.

I am using HTML File API and drag/drop to upload files via XHR post to a PHP script. Procedurally, everything seems to be working OK, however when I try to open the uploaded files, any non-text file is much larger than the source file, and won't open. It's clearly not the same data as was on the source disk. However, text files are exactly the same and open just fine.

有关 3 文件拖放上传的一些示例:文件 1:文本/XML:磁盘 13 KB,上传 13 KB,完美运行文件 2:图像/PNG:在磁盘上 14 KB,上传 18 KB,无法打开文件 3:应用程序/XLSX:磁盘 12 KB,上传 14 KB,打不开

Some examples on a 3-file drag/drop upload:file 1: text/XML: on disk 13 KB, uploaded 13 KB, works perfectlyfile 2: image/PNG: on disk 14 KB, uploaded 18 KB, won't openfile 3: application/XLSX: on disk 12 KB, uploaded 14 KB, won't open

这一切都归结为(在设置 xhr 标头后,文件对象准备就绪等):

It all boils down to this (after xhr headers are setup, file object is ready, etc):

  var reader = new FileReader();
  reader.onload = function(evt) {
    xhr.send(evt.target.result)
  }
  reader.readAsBinaryString(f);

返回大量错误数据.有什么明显的问题吗?

returning large, bad data. Is there anything clearly wrong with it?

推荐答案

这可能是因为您将文件作为二进制字符串读取并手动构建 multipart/form-data 请求.一方面,您不需要使用 FileReader.由于您只想发送内容,请尝试使用 xhr.send(File)xhr.send(FormData).后者为您构造并发送一个 multipart/form-data:

This is probably because you're reading the file as a binary string and constructing the multipart/form-data request manually. For one, you don't need to use FileReader.Since you just want to send the content, try using xhr.send(File) or xhr.send(FormData). The latter constructs and sends a multipart/form-data for you:

function uploadFiles(url, files) {
  var formData = new FormData();

  for (var i = 0, file; file = files[i]; ++i) {
    formData.append(file.name, file);
  }

  var xhr = new XMLHttpRequest();
  xhr.open('POST', url, true);
  xhr.onload = function(e) { ... };

  xhr.send(formData);  // multipart/form-data
}

document.querySelector('input[type="file"]').onchange = function(e) {
  uploadFiles('/server', this.files);
};

这篇关于HTML5 文件 API readAsBinaryString 读取的文件比磁盘上的文件大得多的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 16:59