javascript HTML5 文件 API readAsBinaryString 读取的文件比磁盘上的文件大得多

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6133800/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 19:37:17  来源:igfitidea点击:

HTML5 File API readAsBinaryString reads files as much larger, different than files on disk

javascripthtmlgoogle-chromefile-upload

提问by obrienmd

Full code at https://gist.github.com/992562.

https://gist.github.com/992562 上的完整代码。

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.

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

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

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

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

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

  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?

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

回答by ebidel

This is probably because you're reading the file as a binary string and constructing the multipart/form-datarequest 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-datafor you:

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

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);
};