要求:
我需要使用用户上传的文件进行api调用。我的服务器是node,我使用request模块进行api调用。 下面是用户上传文件并提交时的代码。
if(queryData.sub == "upload"){
var input = {};
var formidable = require('formidable');
var form = new formidable.IncomingForm();
form.parse(request, function (err, fields, files) {
var fs = require('fs');
fs.readFile(files.filetoupload.path, function(err, data) {
input.x_file_content = data;
client.API.ATTACHMENTS.uploadFile(input).then(function(resp){
var str = settings.layoutParsing(resp);
response.write(str);
response.end();
})
});
});
}
}
在上传文件功能中,我使用 FormData 设置文件并在进行 api 调用时发送它。下面是代码:
if (request.x_file_content) {
var FormData = require('form-data');
var formData = new FormData();
formData.append('file', request.x_file_content);//No I18N
req_body = formData;
}
...
var httpclient = require('request');
httpclient({
uri : baseUrl,
method : request.type,
headers : api_headers,
responseType : responseType,
body : req_body
},function(error,response,body){
问题:
但文件未成功发送,并且 api 服务器抛出需要多部分内容的错误。
谁能指出我犯了什么错误。
谢谢!
最佳答案
发现错误
设置标题并替换
fs.readFile(files.filetoupload.path, function(err, data) {
with readStream = fs.createReadStream("文件路径");
更正后的代码:
input.x_file_content = readStream;
..
var FormData = require('form-data');
form_Data = new FormData();
form_Data.append('file', request.x_file_content);//No I18N
req_body = form_Data;
api_headers = form_Data.getHeaders();
关于node.js - 如何使用请求模块在 Node 中的post请求中发送文件数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48667148/