Node.js - 强大的 XHR 上传 [英] Node.js - Formidable upload with XHR
问题描述
我尝试实现一个简单的 XHR 上传到 Node.js(通过 Formidable).问题是如果我设置
I try to implement a simple XHR upload to Node.js (via Formidable). The problem is that if I set
xhr.setRequestHeader("Content-Type", "multipart/form-data");
节点给我错误:
Error: bad content-type header, no multipart boundary
如果我将边界设置为一个随机字符串,则不会发生任何事情.浏览器只是挂在 POST 上并等待服务器响应.
If I set boundary to just a random string nothing happens. The browser just hangs on POST and waits for server response.
关键是,如果我使用强大的常规同步 POST 一切正常.
The point is that if I use formidable with regular synchronous POST everything works fine.
有人尝试将 Formidable 与 XHR 上传一起使用吗?
Anyone tried to use Formidable with XHR upload?
推荐答案
我想通了.我在客户端做了一个小错误.
I figured it out. I made a small bug on the client side.
这是使用 Formidable 上传 XHR 的工作示例
您不需要设置任何边界或特殊标题.
You don't need to set any boundaries or special headers.
客户
var formData = new FormData();
var xhr = new XMLHttpRequest();
var onProgress = function(e) {
if (e.lengthComputable) {
var percentComplete = (e.loaded/e.total)*100;
}
};
var onReady = function(e) {
// ready state
};
var onError = function(err) {
// something went wrong with upload
};
formData.append('files', file);
xhr.open('post', '/up', true);
xhr.addEventListener('error', onError, false);
xhr.addEventListener('progress', onProgress, false);
xhr.send(formData);
xhr.addEventListener('readystatechange', onReady, false);
服务器
app.post('/up', function(req, res) {
var form = new formidable.IncomingForm();
form.uploadDir = __dirname + '/tmp';
form.encoding = 'binary';
form.addListener('file', function(name, file) {
// do something with uploaded file
});
form.addListener('end', function() {
res.end();
});
form.parse(req, function(err, fields, files) {
if (err) {
console.log(err);
}
});
});
这篇关于Node.js - 强大的 XHR 上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!