【问题标题】:Javascript binary file download, and ajax file POST upload in Chrome ExtensionJavascript 二进制文件下载,以及 Chrome 扩展中的 ajax 文件 POST 上传
【发布时间】:2012-12-02 21:40:05
【问题描述】:

我正在编写一个 chrome 扩展内容脚本,它将自己嵌入到某些页面上,当有某些文件类型的链接(.doc、.torrent 等)时,它会下载该文件,然后执行一个文件 POST 到将保存该文件的 python web 服务器。 python服务器正在工作,并处理正常的multipart/form-data POST请求,并在我使用我为它编写的html接口时成功保存了文件。

我有 javascript 正确下载文件:

var req = new XMLHttpRequest();
req.open('GET', 'http://foo.com/bar.torrent', false);
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
var response = req.responseText;

然后当我尝试创建一个 POST 请求并上传它时

// Define a boundary, I stole this from IE but you can use any string AFAIK
var boundary = "---------------------------7da24f2e50046";
var xhr = new XMLHttpRequest();
var body = '--' + boundary + '\r\n'
         // Parameter name is "file" and local filename is "temp.txt"
         + 'Content-Disposition: form-data; name="upfile";'
         + 'filename="temp.torrent"\r\n'
         // Add the file's mime-type
         + 'Content-type: application/bittorrent\r\n\r\n'
         + response + '\r\n';
         //+ boundary + '--';
xhr.open("POST", "http://python.server/", true);
xhr.setRequestHeader(
    "Content-type", "multipart/form-data; boundary="+boundary

);
xhr.onreadystatechange = function ()
{
    if (xhr.readyState == 4 && xhr.status == 200)
        alert("File uploaded!");
}
xhr.send(body);

它认为它上传成功,但是当我尝试打开文件时它说数据已损坏。我认为这是某种编码问题,但我不是 100% 确定。

任何想法都会非常有帮助。

【问题讨论】:

    标签: javascript ajax file-upload google-chrome-extension xmlhttprequest


    【解决方案1】:

    您的上传方法不起作用,因为所有二进制字符都被编码为 UTF-8。我在an answerthis question发布了解释和解决方案。

    在您的情况下,您不需要手动创建帖子数据。以智能方式请求初始数据,并使用FormData 对象发布二进制数据。例如:

    var x = new XMLHttpRequest();
    x.onload = function() {
        // Create a form
        var fd = new FormData();
        fd.append("upfile", x.response); // x.response is a Blob object
    
        // Upload to your server
        var y = new XMLHttpRequest();
        y.onload = function() {
            alert('File uploaded!');
        };
        y.open('POST', 'http://python/server/');
        y.send(fd);
    };
    x.responseType = 'blob';    // <-- This is necessary!
    x.open('GET', 'http://foo.com/bar.torrent', true);
    x.send();
    

    注意:在最初的请求中,我将 false 替换为 true。当也可以异步创建请求时,避免使用同步XMLHttpRequest

    如果你不明白答案,这里有更多的例子和详尽的解释:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-17
      • 2011-06-18
      相关资源
      最近更新 更多