gpt4 book ai didi

node.js 中的 Ajax 文件上传

转载 作者:搜寻专家 更新时间:2023-10-31 22:53:12 27 4
gpt4 key购买 nike

想要使用此 uploader 使用 ajax 上传文件 http://valums.com/ajax-upload/

并在 node.js 中编写这段代码,它可以在没有 ajax 的情况下处理正常的文件上传。

console.log("request " + sys.inspect(req.headers));

req.on('data', function(chunk) {
console.log("Received body data:");
// console.log(chunk.toString());
});
var form = new formidable.IncomingForm();

form.parse(req, function(err,fields, files) {
console.log('in if condition'+sys.inspect({fields: fields, files: files}));
fs.writeFile("upload/"+files.upload.name, files.upload,'utf8', function (err) {
if (err) throw err;
console.log('It\'s saved!');
client.putFile("upload/"+files.upload.name, files.upload.name, function(err, res){
if (err) throw err;
if (200 == res.statusCode) {
console.log('saved to s3');

httpres.writeHead(200, {'content-type': 'text/plain'});
httpres.write('received 1upload:\n\n');
httpres.end();
}
});
});
});

但这会出错吗?

request { host: 'myhost:8001',
'user-agent': 'Mozilla/5.0 (Windows NT 5.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1',
accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'accept-language': 'en-us,en;q=0.5',
'accept-encoding': 'gzip, deflate',
'accept-charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.7',
'keep-alive': '115',
connection: 'keep-alive',
origin: 'http://myhost',
'access-control-request-method': 'POST',
'access-control-request-headers': 'content-type' }

events.js:45
throw arguments[1]; // Unhandled 'error' event
^
Error: bad content-type header, no content-type
at IncomingForm._parseContentType (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:196:17)
at IncomingForm.writeHeaders (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:109:8)
at IncomingForm.parse (/usr/local/lib/node/.npm/formidable/1.0.0/package/lib/formidable/incoming_form.js:65:8)
at Server.<anonymous> (/home/myfolder/myfolder/newcontentserver.js:29:18)
at Server.emit (events.js:67:17)
at HTTPParser.onIncoming (http.js:1108:12)
at HTTPParser.onHeadersComplete (http.js:108:31)
at Socket.ondata (http.js:1007:22)
at Socket._onReadable (net.js:678:27)
at IOWatcher.onReadable [as callback] (net.js:177:10)

我认为问题是内容类型未通过 ajax 文件上传设置在 header 中。这就是为什么出现此错误我如何在此 uploader 中设置 header ,或者如何在 node.js 服务器中创建文件通过传入的数据。因为它使用的是 xhr,所以我想我不能使用 formidable.incomingform() 我应该使用什么?

最佳答案

正在看最新fileuploader.js source code on github他确实设置了内容类型

xhr.setRequestHeader("Content-Type", "application/octet-stream");

我相信您的问题出在其他地方。

关于node.js 中的 Ajax 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5988727/

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