在Node.js中使用POST请求上传文件 [英] Uploading file using POST request in Node.js
问题描述
我在Node.js中使用POST请求上传文件时遇到问题。我必须使用 request
模块来完成它(没有外部的npms)。服务器需要使用包含文件数据的文件
字段进行多部分请求。在没有使用任何外部模块的情况下,在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);
}
});
推荐答案
看起来你已经在使用 request
module 。
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
模块,内部由<$ c $使用c>请求。
For more information on posting multipart/form-data
see node-form-data
module, which is internally used by request
.
这篇关于在Node.js中使用POST请求上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!