在 Node.js 中使用 POST 请求上传文件 [英] Uploading file using POST request in Node.js
问题描述
我在 Node.js 中使用 POST 请求上传文件时遇到问题.我必须使用 request
模块来完成(没有外部 npms).服务器需要它是包含文件数据的 file
字段的多部分请求.在不使用任何外部模块的情况下,在 Node.js 中似乎很容易做起来却非常困难.
I have problem uploading file using POST request in Node.js. I have to use request
module to accomplish that (no external npms). Server needs it to be multipart request with the file
field containing file's data. What seems to be easy it's pretty hard to do in Node.js without using any external module.
我试过使用这个例子但没有成功:
I've tried using this example but without success:
request.post({
uri: url,
method: 'POST',
multipart: [{
body: '<FILE_DATA>'
}]
}, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
推荐答案
看起来你已经在使用 请求
模块.
Looks like you're already using request
module.
在这种情况下,您只需要发布 multipart/form-data
就是使用它的 表单
功能:
in this case all you need to post multipart/form-data
is to use its form
feature:
var req = request.post(url, function (err, resp, body) {
if (err) {
console.log('Error!');
} else {
console.log('URL: ' + body);
}
});
var form = req.form();
form.append('file', '<FILE_DATA>', {
filename: 'myfile.txt',
contentType: 'text/plain'
});
但是如果你想从你的文件系统中发布一些现有的文件,那么你可以简单地将它作为可读流传递:
but if you want to post some existing file from your file system, then you may simply pass it as a readable stream:
form.append('file', fs.createReadStream(filepath));
request
将自行提取所有相关元数据.
request
will extract all related metadata by itself.
有关发布 multipart/form-data
的更多信息,请参阅 node-form-data
模块,由 request
内部使用.
For more information on posting multipart/form-data
see node-form-data
module, which is internally used by request
.
这篇关于在 Node.js 中使用 POST 请求上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!