文件上传填充req.body但不填充req.file

问题描述 投票:-1回答:2

我已经使用multer和express创建了一个文件上传API,它通过POSTMAN工作正常,但是当我尝试使用另一个文件上传API调用相同的api时,它无法正常工作:

我的代码如下,在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();

在上面的代码中,当我通过postman调用API时,我的req.file被填充。

但是使用下面的代码调用上面的API并没有填充第一个API的req.file,它是未定义的。我也试过使用form-data npm模块而没有任何运气:

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)
    })
}
javascript node.js express multer
2个回答
0
投票
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);
});

}

0
投票

我在这篇文章的帮助下解决了它:how to upload file saved in memory by multer to another API

var stream = require('stream')

const { Duplex } = stream;
function bufferToStream(buffer) {
   const duplexStream = new Duplex();
   duplexStream.push(buffer);
   duplexStream.push(null);
   return duplexStream;
}

request.post({
       headers: { 'enctype': 'multipart/form-data;boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' },
       url: "http://localhost:7022/nuxeo/upload",
            formData: {
                file: {
                    value: bufferToStream(req.file.buffer),
                    options: {
                        filename: req.file.originalname,
                        contentType: req.file.mimetype,
                        knownLength: req.file.size
                    }
                },
                path: '/FCA/DT/clause32a'
            }
        }, function (error, response, body) {
            if (error) { return next(error) 
            res.send(JSON.parse(body))
        })
© www.soinside.com 2019 - 2024. All rights reserved.