从Node js传递接收到的.csv文件到其他服务器

时间:2018-08-03 12:32:45

标签: node.js forms

我正在尝试将.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);
}

我可以看到错误为:

  

“内容类型中没有多部分边界参数”

如何将此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' }

另一种方法

我尝试直接传递文件,而不是像这样创建FormData():

        const options = {
                upload: req.file,
                headers: {
                    authorization: req.headers.svctoken,
                    'Content-type': 'multipart/form-data'
                },
                json: true
        };

但错误仍然存​​在

2 个答案:

答案 0 :(得分:0)

对此,我同意https://stackoverflow.com/users/3648693/noobtw的要求,尚不清楚您要使用哪个库来发出请求。话虽如此,看来您可能正在使用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);
});

要使用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);
}); 

希望这会有所帮助。

答案 1 :(得分:0)

(来自g++ -std=c++11 -c Implementation.cpp g++ -o main main.o Implementation.o Client.o -std=c++11 documentation

form-data

因此您的In Node.js environment you need to set boundary in the header field 'Content-Type' by calling method `getHeaders` 应该从Content-type动态生成,而不是手动设置为csvForm.getHeaders()。这将导致表单边界也包括在内容类型中,例如。

multipart/form-data