如何通过Axios上传与FormData一起发送的文件? (TypeError:file.mv不是函数)

时间:2020-06-11 01:45:29

标签: javascript node.js express axios form-data

因此,我正在使用Axios将文件从一台服务器发送到另一台服务器,一个是应用程序后端,另一个是区块链服务器。

我要在哪里发送文件:

router.post("/acme/:id", auth, async (req, res) => {

    var formData = new FormData();
    console.log(req.files.file)
    formData.append("image", req.files.file.data);
    var Response;

    try {
      Response = await axios.post(BC_SERVER + "acmeDataFileUpload", {
        id: req.params.id,
        data: formData,
        headers: {
            'Content-Type': 'multipart/form-data'
          }
      });

    } catch (error) {
      console.log("Error BlockChain");
    }

    try {
      res.status(201).send("ok");
    } catch (e) {
      res.status(500).send(e);
    }
  });

Axios将其发送到哪里:

app.post('/acmeDataFileUpload', async (req, res) => {        
    const id_owner = req.body.id;
    console.log(req.body)
    const file = req.body.data;
    const fileName = id_owner;  
    const filePath = 'files/' + fileName;
    console.log(fileName);

    file.mv(filePath, async (err) => {
        try {
            const fileHash = await addFile(fileName, filePath);
            fs.unlink(filePath, (err) => {
                if (err) console.log(err);
            });
            const json = '{"dataType": "Object" , "local": "'+localServer+fileHash+'",' +'"ipfsServer": "'+ipfsServer+fileHash+'"}';
            console.log(json);
            const obj = JSON.parse(json);
            res.status(201).send(obj);
        } catch (err) {
            console.log('Error : failed to download file');
            console.log(err);
            return res.status(500).send(err);
        }
    });


});

这就是req.body的日志:

{
  id: '5ec2b7d47ae93a49ecb773f6',
  data: {
    _overheadLength: 144,
    _valueLength: 579564,
    _valuesToMeasure: [],
    writable: false,
    readable: true,
    dataSize: 0,
    maxDataSize: 2097152,
    pauseStreams: true,
    _released: false,
    _streams: [
      '----------------------------383350625990492694059785\r\n' +
        'Content-Disposition: form-data; name="image"\r\n' +
        'Content-Type: application/octet-stream\r\n' +
        '\r\n',
      [Object],
      null
    ],
    _currentStream: null,
    _insideLoop: false,
    _pendingNext: false,
    _boundary: '--------------------------383350625990492694059785'
  },
  headers: { 'Content-Type': 'multipart/form-data' }
}

基本上我在这里发送缓冲区,因为FormData不接受文件并告诉我 source.on不是函数,我宁愿将图像发送到req.files req.body中,Axios确实让我感到困惑。

1 个答案:

答案 0 :(得分:1)

headers: formData.getHeaders()