我正在研究「multiple ajax uloader」。在流血的瀏覽器(Chrome 6,Firefox 4)中運行良好。但在Firefox 3.6中,我必須手動創建輸出字符串,因此該瀏覽器不支持FormData對象。XmlHttpRequest在Firefox 3.6中使用「Content-Type:multipart/form-data」破壞標頭
我跟着很多教程,特別是this。作者通知正確設置標題&要發送的內容。我仔細地遵循這個建議,但Firefox 3.6失敗了我的努力。
這是頭和身體的正確的設置(通過提交簡單的靜態形式捕獲): correct headers,correct body
這是我得到的,當我使用Firefox的XHR對象提交相同的數據: wrong headers,wrong body
正如你所見,xhr的頭文件已損壞。這導致文件上傳完全失敗。下面是一個代碼我使用:
function generateBoundary()
{
var chars = '',
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是腐敗的標題這樣?