【问题标题】:XmlHttpRequest corrupts headers in Firefox 3.6 with "Content-Type:multipart/form-data"XmlHttpRequest 使用“Content-Type:multipart/form-data”破坏 Firefox 3.6 中的标头
【发布时间】: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


    【解决方案1】:

    我是范围问题。我尝试在 WinXP 下的全新 Firefox 安装中使用代码(我的主要系统是 Arch Linux)。问题依然存在。我发现Mozilla's xhr 有一个名为“multipart”的附加属性。将此设置为 true 后,标题就可以了,但我的 xhr.events 没有被触发 - 发送文件后 JS 崩溃。

    我使用 Firebug 的 JS 调试器进行了更深入的研究,发现在xhr.multipart = true; 代码跳转到 jQuery 库的深水区之后,在一些奇怪的事件周围会发生奇怪的事情。

    更令人好奇的是,标题/内容在 Firebug 的控制台中似乎是正确的,但在 HttpFox 扩展中,它已损坏。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 2013-03-12
      • 1970-01-01
      • 2012-02-27
      • 1970-01-01
      • 2019-02-25
      • 1970-01-01
      相关资源
      最近更新 更多