【发布时间】:2010-07-16 22:44:09
【问题描述】:
我正在研究“多个 ajax uloader”。在最前沿的浏览器(Chrome 6、Firefox 4)中运行良好。但是在 Firefox 3.6 中我必须手动创建要发送的输出字符串,因为这个浏览器不支持 FormData 对象。
我学习了很多教程,尤其是this。作者通知要发送的标题和正文内容的正确设置。我仔细遵循了这个建议,但 Firefox 3.6 失败了。
这是标题和正文的正确设置(通过提交简单的静态表单捕获): correct headers, correct body
当我使用 Firefox 的 xhr 对象提交相同的数据时,这就是我得到的: wrong headers, wrong body
如您所见,xhr 的标头已损坏。这导致文件上传完全失败。这是我使用的代码:
function generateBoundary()
{
var chars = '0123456789',
out = '';
for( var i = 0, len = chars.length; i < 30; i++) {
out += chars[Math.floor(Math.random()*len)];
}
return '----' + out;
}
function getMultipartFd(file, boundary)
{
var rn = '\r\n',
body = '';
body = boundary + rn;
body += 'Content-Disposition: form-data; name="Files[]"; filename="' + file.name + '"' + rn;
body += 'Content-Type: ' + file.type + rn + rn;
body += file.getAsBinary() + rn;
return body;
}
$(function(){
$startUpload.click(function(){
var url = $uploadForm.attr('action'),
xhr = new XMLHttpRequest(),
boundary = generateBoundary(),
file = null,
body = '';
file = $SOME_ELEMENT_WITH_ATTACHED_FILE.file;
body = getMultipartFd(file, boundary);
console.info(file);
console.info(body);
xhr.upload.onload = function(){
console.info('done');
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
xhr.sendAsBinary(body + boundary + '--' + '\r\n');
return false;
});
});
这里也是文件和正文变量的转储: dump file, dump body
有人知道,为什么 xhr 会以这种方式破坏标头?
【问题讨论】:
标签: ajax upload file-upload xmlhttprequest header