如何从节点中的请求表单数据接收req.file

时间:2019-01-09 16:06:56

标签: node.js request multer form-data

我有两个API,我想使用request和formData从第一个API发送文件。

如何从请求表单数据接收req.file?

接收辅助代码

var storage = multer.diskStorage({
destination: function (req, file, cb) {
    mkdirp(configServer.dataDir+ "/tmp", function(err){
       cb(null, configServer.dataDir+ "/tmp/")
    })
},
filename: function (req, file, cb) {
    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("file : ", req.file)
     console.log("body : ", req.body)
     res.json({success: true})


})

}

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

发送附带代码

  var storage2 = multer.diskStorage({
    destination: function (req, file, cb) {
        mkdirp(config.dataDir+ "/tmp", function(err){
            cb(null, config.dataDir+ "/tmp/")
        })
    },
    filename: function (req, file, cb) {
         cb(null, file.fieldname + '-' + Date.now())
    }
})

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

exports.user_coffre_fort_create_file2 = function (req, res) {

    upload2(req, res, function (err) {
        var obj = {

            'Nom': "Lagaf",
            'Prénom': "Vincent",
            'Date de naissance': "13/01/1960",
            'file':new Buffer(fs.readFileSync(req.file.path)).toString("base64")
     }

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

这就是我收到的 req.file为空,我在正文中收到文件

如何在req.file中接收文件?

预先感谢

  file : undefined

    body :  {
  'Nom: 'Lagaf',
   'Prénom': 'Vincent',
  'Date de naissance': '13/01/1960',
  file:/9j/4gIcSUNDX1BST0ZJTEUAAQEAAAIMbGNtcwIQAABtbnRyUkdCIFhZWiAH3AABABkAA

1 个答案:

答案 0 :(得分:0)

您需要使用multipart/form-data作为内容类型,以便从requests模块上载文件和表单功能。看看this answer