Javascript的二进制文件下载,并在Chrome扩展AJAX文件的POST上传并在、上传、二进制文件、文件

2023-09-10 19:55:52 作者:青衫泪

我正在写一个Chrome扩展的内容脚本,将自身嵌入在一些网页上,当有特定的文件类型链接(doc和的.torrent等),它会下载该文件,然后执行一个文件POST到一个Python Web服务器将保存该文件。蟒蛇服务器的工作,并处理正常的multipart / form-data的POST请求,并成功地保存文件时,我用的是HTML界面我写吧。

I'm writing a chrome extension content script which will embed itself on some pages, and when there are certain file type links (.doc, .torrent, etc) it will download that file, and then do a file POST to a python web server which will save that file. The python server is working, and handles a normal multipart/form-data POST request, and successfully saves the file when I use the html interface I wrote for it.

我的JavaScript下载该文件正确:

I have javascript downloading the file properly:

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请求,并把它上传

And then when I try to create a POST request and upload it

// 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%肯定。

It thinks that it uploaded successfully, but when I try to open the file it says the data is corrupted. I think this is some kind of encoding issue, but I'm not 100% sure.

任何想法,将是非常有益的。

Any thoughts would be very helpful.

推荐答案

您上传的方法是行不通的,因为所有的二进制字符都设有codeD为UTF-8。我张贴在an回答在this问题。

Your upload method does not work, because all binary characters are encoded as UTF-8. I posted the explanation and solution in an answer at this question.

在你的情况,你不需要手动创建后的数据。要求初始数据的一个巧妙的方法,并使用 FORMDATA 对象发布的二进制数据。例如:

In your case, you don't need to manually create the post data. Request the initial data in a smart way, and use the FormData object to post the binary data. For instance:

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();

注:我换成在初始请求。避免使用同步 XMLHtt prequest 时,它也可以以异步方式创建请求。

Note: I replaced false with true at the initial request. Avoid using synchronous XMLHttpRequest when it's also possible to asynchronously create the request.

如果你不明白的回答,这里有更多的例子进行彻底的解释:

If you don't understand the answer, here are more examples with thorough explanations:

XMLHtt$p$pquest:多重/相关POST XML和形象的有效载荷 - FORMDATA 未使用,但后期的数据手动创建的,而不是 上传的谷歌浏览器扩展名的文件 - 样本浏览器扩展程序,它使用的Web Workers(带FORMDATA polyfill)上传文件 Google镀铬重新宿主图像扩展 - 从网页擦伤的图像,并上传影像使用Chrome扩展到imgur XMLHttpRequest: Multipart/Related POST with XML and image as payload - FormData is not used, but the post data is manually created instead. Upload a File in a Google Chrome Extension - A sample Chrome extension which uses Web Workers (with a FormData polyfill) to upload files Google chrome rehost image extension - Scrapes an image from the page, and upload the image to imgur using a Chrome extension.