本文介绍了HTML5 File API readAsBinaryString读取文件的大小与磁盘上的文件不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
上的完整代码。
我正在使用HTML File API,并通过拖放操作将文件通过XHR张贴到PHP脚本中。程序上,一切似乎工作正常,但是当我尝试打开上传的文件时,任何非文本文件比源文件大得多,不会打开。这显然不是源数据盘上的数据。然而,文本文件是完全相同的,打开就好了。
3个文件拖放上传的一些例子:
file 1:text / XML :磁盘上13 KB,上传13 KB,完美工作
文件2:image / PNG:磁盘上14 KB,上传18 KB,不会打开
文件3:application / XLSX:磁盘上12 KB,上传14 KB,不会打开
这一切归结于此(在xhr头文件安装后,文件对象准备就绪等):
var reader = new FileReader();
reader.onload = function(evt){
xhr.send(evt.target.result)
}
reader.readAsBinaryString(f);
返回较大的错误数据。有没有什么明显的错误呢?
解决方案
这可能是因为你正在阅读文件作为一个二进制字符串和构造 multipart / form-data
手动请求。首先,你不需要使用 FileReader
。
由于您只是想发送内容,请尝试使用 xhr.send(File)
或 xhr.send(FormData)
。后者构造并为您发送 multipart / form-data
:
function uploadFiles(url,files){
var formData = new FormData();
$ b $ 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); //多部分/表单数据
}
document.querySelector('input [type =file]')。onchange = function(e){
uploadFiles(' / server',this.files);
};
Full code at 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.
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
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?
解决方案
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 File API readAsBinaryString读取文件的大小与磁盘上的文件不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!