如何在节点js中使用multer将文件发送到api?

时间:2019-01-08 15:59:49

标签: node.js request multer form-data

我想使用两个API将文件从服务器发送到另一台服务器,其中一个api上传到最终服务器,另一个api读取表单数据并将其发送到调用第一个api的api

上传到最终服务器

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        mkdirp(configServer.dataDir+ "/tmp", function(err){
            console.log("err * : ", err)
            if(err)
                res.json({success:false, error:err})
            cb(null, configServer.dataDir+ "/tmp/")
        })
    },
    filename: function (req, file, cb) {
        console.log("file**", file)
        cb(null, file.fieldname + '-' + Date.now())
    }
})

var upload = multer({ storage: storage }).single('file');

exports.upload_in_server = function (req, res) {

    upload(req, res, function (err) {

         console.log("body : ", req.body)
         console.log("file : ", req.file)

        if (err instanceof multer.MulterError) {
            // A Multer error occurred when uploading.
            console.log("err 1 : ", err)
        } else if (err) {
            // An unknown error occurred when uploading.
            console.log("err 2 : ", err)
        }

         res.json({success: true})

    })

}

router.post("/myurl/uploadInServer",  UserController.upload_in_server);

接下来,调用api将文件发送到最终服务器

var storage2 = multer.diskStorage({
    destination: function (req, file, cb) {
        mkdirp(config.dataDir+ "/tmp", function(err){
            console.log("err * : ", err)
            if(err)
                res.json({success:false, error:err})
            cb(null, config.dataDir+ "/tmp/")
        })
    },
    filename: function (req, file, cb) {
        console.log("file**", file)
        cb(null, file.fieldname + '-' + Date.now())
    }
})

var upload2 = multer({ storage: storage2 }).single('file');

exports.user_coffre_fort_create_file2 = function (req, res) {

var querystring = require('querystring');

    upload2(req, res, function (err) {

        if (err instanceof multer.MulterError) {
            // A Multer error occurred when uploading.
            console.log("err 1 : ", err)
        } else if (err) {
            // An unknown error occurred when uploading.
            console.log("err 2 : ", err)
        }

        var FormData = require('form-data');

        var form = new FormData();

        const encoded = req.file.toString('base64')

        form.append('file', encoded);

        form.append('Name', "Lagaf");
        form.append('Surname', "Vincent");
        form.append('birthdate', "13/01/1960");

        request({
            url: "/myurl/uploadInServer",
            method: 'POST',
            json: querystring.stringify(form),
            headers: {"Content-Type": "application/x-www-form-urlencoded", "Authorization": my_tokentoken}
            //
        }, function (err, stdout, body) {
            res.json({success:true})
        })
    })
}

这是我在服务器中收到的消息,正文不正确,文件未定义

body :  { '"_overheadLength': '420',
  _valueLength: '37',


writable: 'false',
  readable: 'true',
  dataSize: '0',
  maxDataSize: '2097152',
  pauseStreams: 'true',
  _released: 'false',
  _streams: 
   [ '----------------------------081543624686364985445462\r\nContent-Disposition: form-data; name="file"\r\n\r\n',
     '[object Object]',
     '',
     '----------------------------081543624686364985445462\r\nContent-Disposition: form-data; name="Name"\r\n\r\n',
     'Lagaf',
     '',
     '----------------------------081543624686364985445462\r\nContent-Disposition: form-data; name="Surname"\r\n\r\n',
     'Vincent',
     '',
     '----------------------------081543624686364985445462\r\nContent-Disposition: form-data; name="birthdate"\r\n\r\n',
     '13/01/1960',
     '' ],
  _currentStream: '',
  _boundary: '--------------------------081543624686364985445462"' }
files :  undefined

如何具有正确的正文和不是undefined的“ req.file”。

1 个答案:

答案 0 :(得分:0)

将二进制文件转换为base64编码的字符串有什么原因吗?为什么使用urlencoded代替multipart/form-data

尝试:

request({
    url: "/myurl/uploadInServer",
    method: 'POST',
    formData : {
        file: req.file,
        'Name': 'Lagaf',
        'Surname': 'Vincent',
        'birthdate': '13/01/1960'
    },
    headers: {
        "Content-Type": "multipart/form-data"
        "Authorization": my_tokentoken
    }
}, function (err, stdout, body) {
    res.json({success:true})
})