我必须制作一个纯粹轻量级的javascript / html5函数来上传文件。
它差不多完成但是现在当我选择一个文件时,它将在服务器上创建一个具有相同名称的空白文件
我检查并看到filereader
api访问该文件
请参阅以下说明:
function uploadFileViaXHR(file){
var boundary = "-------boundary";
var content = '--' + boundary + '\r\n';
content += 'Content-Disposition: form-data; name="file";';
content += 'filename="' + encodeURIComponent(file.name) + '"';
content += '\r\nContent-Type: application/octet-stream\r\n';
content += '\r\n';
reader = new FileReader();
reader.readAsBinaryString(file);
content += reader.result;
content += '\r\n--' + boundary + '--\r\n';
console.log(content);
var xhr = new XMLHttpRequest();
onUploadBegin(elemId, xhr, file.name, file.size);
$('#' + elemId).addClass('html5');
xhr.upload.onabort = function(e) { onUploadAbort(elemId, e); };
xhr.upload.onerror = function(e) { onUploadError(elemId, e); };
xhr.upload.onprogress = function(e) { onUploadProgress(elemId, e); };
xhr.onload = function(e) { onUploadComplete(elemId, e); };
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "multipart/form-data; boundary=" + boundary);
xhr.setRequestHeader("Cache-Control", "no-cache");
// pseudo standard fields.
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
xhr.setRequestHeader("X-File-Name", file.name);
xhr.setRequestHeader("Content-Length", file.fileSize);
xhr.sendAsBinary(content);
}
此文件本地输出适用于console.log
---------boundary
Content-Disposition: form-data; name="file";filename="145792_748.jpg"
Content-Type: application/octet-stream
null
---------boundary--
并在服务器端创建一个空文件
当我改变这一行时:
content += reader.result;
至content += reader;
本地出局是
---------boundary
Content-Disposition: form-data; name="file";filename="145792_748.jpg"
Content-Type: application/octet-stream
[object FileReader]
---------boundary--
和服务器制作内容为[object FileReader]
的文件!!
我该如何解决这个问题?
答案 0 :(得分:1)
使用FormData
代替读取文件。
更简单
您也可以发送带有文件的外部数据fd.append( 'field1', 'aaaa' );
function uploadFileViaXHR(file){
fd = new FormData();
fd.append( 'field1', 'aaaa' );
fd.append( 'file', file );
var xhr = new XMLHttpRequest;
xhr.open('POST', url, true);
onUploadBegin(elemId, xhr, file.name, file.size);
$('#' + elemId).addClass('html5');
xhr.upload.onabort = function(e) { onUploadAbort(elemId, e); };
xhr.upload.onerror = function(e) { onUploadError(elemId, e); };
xhr.upload.onprogress = function(e) { onUploadProgress(elemId, e); };
xhr.onload = function(e) { onUploadComplete(elemId, e); };
xhr.send(fd);
}