如何下载然后上传文件?
尝试使用以下代码,但无法正常工作:
// download the file first
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
// upload the file
req.open("POST", "http://mysite.com/upload", false);
req.setRequestHeader("Content-Length", req.responseText.length);
req.sendAsBinary(req.responseText); // What should I pass here?
if (req.status != 200) return '';
return req.responseText;
sendAsBinary is firefox function 。
更新。我也尝试将其作为表单的一部分上传:
var response = req.responseText;
var formData = new FormData();
formData.append("file", response);
req.open("POST", "http://mysite.com/upload", false);
req.send(formData);
但服务器仍然没有收到完整的数据。
Tried to use the following code, but it doesn't work properly:
// download the file first
var req = new XMLHttpRequest();
req.open('GET', url, false);
req.overrideMimeType('text/plain; charset=x-user-defined');
req.send(null);
if (req.status != 200) return '';
// upload the file
req.open("POST", "http://mysite.com/upload", false);
req.setRequestHeader("Content-Length", req.responseText.length);
req.sendAsBinary(req.responseText); // What should I pass here?
if (req.status != 200) return '';
return req.responseText;
sendAsBinary is firefox function.
Upd. Also I've tried to upload that as part of the form:
var response = req.responseText;
var formData = new FormData();
formData.append("file", response);
req.open("POST", "http://mysite.com/upload", false);
req.send(formData);
But still not full data is received by the server.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最后我使用了临时文件的方法:
Finally I've used the approach with temp file:
在重用
req
对象之前,您需要将responseText
存储在中间变量中。更新
根据MDN页面使用XMLHttpRequest,它看起来像上面的代码行不通的。以下是获取二进制响应的正确方法。最后,您将得到一个无符号整数数组,您可以将其发送回服务器并转换为二进制。我认为。
更新 2
要将
byteArray
提交到服务器,我会尝试类似以下未经测试、几乎保证不起作用的代码。更新 3
可以从 JavaScript 模块/ XPCOM 使用 XMLHttpRequest组件与您的问题有什么关系?
You need to store the
responseText
in an intermediate variable before reusing thereq
object.Update
Per the MDN page Using XMLHttpRequest, it looks like the above code won't work. Following is the proper way to get the binary response. In the end, you will have an array of unsigned integers which you could send back to the server and convert to binary. I think.
Update 2
To submit the
byteArray
to a server, I would try something like the following untested, almost guaranteed not to work code.Update 3
Could Using XMLHttpRequest from JavaScript modules / XPCOM components have anything to do with your issue?