我正在尝试将.csv节点js中的文件发送到另一台服务器
uploadCSVData = async(
req: Request,
res: Response,
next: any
):Promise<any> =>{
const csvForm = new FormData();
csvForm.append('upload', fs.createReadStream(req.file.path));
console.log(csvForm);
const options = {
upload: csvForm,
headers: {
authorization: req.headers.svctoken,
'Content-type': 'multipart/form-data'
},
json: true
};
const response = await this.postSvc.exec(
['https://come/svc', `someAPI?id=${req.body.acntID}`]
.join('/'),
options
);
return res.status(200).json(response.body);
}
Run Code Online (Sandbox Code Playgroud)
我可以看到错误:
"Content-Type中没有多部分边界参数"
如何将此发送req.file到另一个期望的服务器'multipart/form-data'
我不认为boundary在使用时明确添加是一个好主意form-data
在csvForm控制台日志下面是:
FormData {
_overheadLength: 167,
_valueLength: 0,
_valuesToMeasure:
[ ReadStream {
_readableState: [ReadableState],
readable: true,
_events: [Object],
_eventsCount: 3,
_maxListeners: undefined,
path: 'uploads\\1533537127411_sample1.csv',
fd: null,
flags: 'r',
mode: 438,
start: undefined,
end: Infinity,
autoClose: true,
pos: undefined,
bytesRead: 0,
closed: false,
emit: [Function] } ],
writable: false,
readable: true,
dataSize: 0,
maxDataSize: 2097152,
pauseStreams: true,
_released: false,
_streams:
[ '----------------------------481765298048352594095608\r\nContent-Disposition: form-data; name="upload"; filename="1533537127411_sample1.csv"\r\nContent-Type: text/csv\r\n\r\n',
DelayedStream {
source: [ReadStream],
dataSize: 0,
maxDataSize: Infinity,
pauseStream: true,
_maxDataSizeExceeded: false,
_released: false,
_bufferedEvents: [Array],
_events: [Object],
_eventsCount: 1 },
[Function: bound ] ],
_currentStream: null,
_boundary: '--------------------------481765298048352594095608' }
Run Code Online (Sandbox Code Playgroud)
我尝试直接传递文件而不是创建FormData(),如:
const options = {
upload: req.file,
headers: {
authorization: req.headers.svctoken,
'Content-type': 'multipart/form-data'
},
json: true
};
Run Code Online (Sandbox Code Playgroud)
但错误仍然存在
我对此表示同意/sf/users/255408541/,目前尚不清楚您使用哪个库来发出请求。话虽如此,看起来您可能正在使用https://www.npmjs.com/package/form-data来处理表单数据。
查看该模块的文档,似乎不需要Content-Type在发出请求时显式添加标头。只需使用实例submit的方法form来发送数据即可。请注意,下面的示例来自表单数据模块文档:
csvForm.submit({
host: 'example.com',
path: '/your-path',
headers: { authorization: req.headers.svctoken }
}, function(err, res) {
console.log(res.statusCode);
});
Run Code Online (Sandbox Code Playgroud)
要使用Request库传递带有 formData 的文件,您可以执行以下操作:
const formData = {
my_field: 'my_value',
upload: fs.createReadStream(req.file.path),
};
request.post({url:'https://yourservice.com/upload', formData: formData}, function(err, httpResponse, body) {
if (err) {
return console.error('upload failed:', err);
}
console.log('Upload successful! Server responded with:', body);
});
Run Code Online (Sandbox Code Playgroud)
希望这有帮助。
| 归档时间: |
|
| 查看次数: |
419 次 |
| 最近记录: |