首页 > 解决方案 > File upload populating req.body but not req.file

问题描述

I have created a file upload API using multer and express which works fine through POSTMAN but when i try to call the same api using another file upload API, it's not working:

My code is as follows which runs on http://localhost:7022/nuxeo/upload:

module.exports.upload = function (req, res, next) {
    var path = req.body.path
    var uploadFile = req.file; //get uploaded file
    var stream = streamifier.createReadStream(req.file.buffer) //create a stream from file buffer
    var blob = new Nuxeo.Blob({   //create a blob from file stream
        content: stream,
        name: uploadFile.originalname,
        mimeType: uploadFile.mimetype,
        size: uploadFile.size
    });
    var batch = nuxeo.batchUpload();

In the above code when I call the API through postman, my req.file is populated.

But calling the above API using the code below doesn't populate the req.file of the first API, it is undefined. I have also tried using form-data npm module without any luck :

module.exports.attach = function(req,res,next){
    var uploadfile = req.file  //file is populated here
    formData = { 'file' : uploadfile, 'path' : '/FCA/DT/clause32a'}
    var opts = {
        url: "http://localhost:7022/nuxeo/upload",
        headers: { 'enctype':  'multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
        json: true,
        body: formData
    };
    request.post(opts,function(err,response,body){
        console.log(body)
    })
}

标签: javascriptnode.jsexpressmulter

解决方案


module.exports.attach = function(req,res,next){
    var uploadfile = req.file  //file is populated here
    var fs = require('fs');
var request = require('request');
request.post({
    url: <URL>,
    formData: {
        file: fs.createReadStream(<FILE_PATH>),
        filetype: <FILE_TYPE>,
        filename: <FILE_NAME>,
        title: <FILE_TITLE>,
    },
}, function(error, response, body) {
    console.log(body);
});

}

推荐阅读