gpt4 book ai didi

Javascript 二进制文件下载,以及 Chrome 扩展中的 ajax 文件 POST 上传

转载 作者:行者123 更新时间:2023-11-29 22:18:14 25 4
gpt4 key购买 nike

我正在编写一个 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% 确定。

任何想法都会很有帮助。

最佳答案

您的上传方法不起作用,因为所有二进制字符都被编码为 UTF-8。我在an answer贴出了解释和解决方法在 this 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

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

关于Javascript 二进制文件下载,以及 Chrome 扩展中的 ajax 文件 POST 上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13886274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com