在node.js中使用multer上载多个文件的服务

时间:2019-01-22 11:03:07

标签: node.js express file-upload postman multer

我创建了一个名为FileUpload的类,并使用multer创建了一个上传多个文件的函数。我想在控制器中使用此方法,但我不能这样做。我无法从请求中获取其他字段。 这是FileUpload类:

var multer = require('multer');

class FileUpload{
constructor(){
    this.storage = null;
    this.filepath = null;
    this.upload = null;
}

uploadMultipleFile(req,res,path){
    this.filepath = path;
    this.storage = multer.diskStorage({
        destination : (req,file,callback) =>{
            callback(null,path)
        },
        filename : (req,file,callback)=>{
            this.filepath = this.filepath +  file.fieldname + '-' + new Date().getTime();
            callback(null,this.filepath);
        }
    });
    this.upload = multer({storage:this.storage}).array('files',req.files.length);
    this.upload(req,res,(err) => {
        if(err){
            return res.status(403).send({
                    success:false,
                    message : SystemMessage.UploadErrorMessage.replace('{0}',"Files"),
                    data : {
                        filepath : filepath 
                    }

            });
        }
        return res.status(200).send({
            success:true,
            message : SystemMessage.UploadSuccessMessage.replace('{0}',"Files"),
            data : {
                filepath : filepath 
            }
        });
    });

}
}

module.exports = FileUpload;

这是我在其中定义路由的控制器文件:

const express = require('express');
const router = express.Router();
const FileUpload = require('../services/fileUpload');

router.post("/add",(req,res)=>{
let localdate=CommonFunction.datetime();
let fileUpload = new FileUpload();
let obj = {
   user_id:req.body.user_id,
   subject:req.body.subject,
   message:req.body.message,
   created_date:localdate,
   modified_date:localdate
 };

 });

当我从邮递员那里呼叫这条路线时,我在body.form中使用表格数据格式。我得到以下响应:

{  
   user_id: undefined, 
   subject: undefined,
   message: undefined,
   created_date: '2019-1-22 13:55:42',
   modified_date: '2019-1-22 13:55:42' 
}

指导我如何在路由/ add中使用uploadMultipleFile函数?

1 个答案:

答案 0 :(得分:0)

在定义文件上传路由器时,您可以将multer用作中间件

在路由器文件中

var multer  = require('multer');
var path = require('path');
var storage = multer.diskStorage({
    destination: 'public/upload/', // uploading directory 
    filename: function ( req, file, cb ) { //cahnge file name
        let ext = (path.extname(file.originalname)).toLowerCase(); //get file extension
        let time = Date.now(); //get timestamp
        cb( null, 'vehicle-'+time+ext); //return renamed file
    }
});

var upload = multer( { storage: storage } );

router.post('/add',upload.any(), function (req,res){ // any() will accept files that comes over the wire. An array of files will be stored in req.files
    uploadMultipleFile(req, res); //or redirect to your controller as you normal do
});

现在转到您的控制器(uploadMultipleFile(req,res))文件。

uploadMultipleFile(req, res){
    console.log(req.files); //see your files in console
    // in req.files files are available do what stuff you want
    // you can use loop function to save files details in your database
    // you can get single file like this 'your uploaded directory/'+req.file[0].filename;
}