在 node.js 中使用 multer 上传多个文件的服务 [英] Service for uploading multiple file using multer in node.js

查看:34
本文介绍了在 node.js 中使用 multer 上传多个文件的服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I have created class named FileUpload and made one function to upload multiple files using multer.I want to use this method in controller but i cannot to do so. i can not get other fields from request. Here is the FileUpload class :

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;

Here is the controller file in which i have defined route:

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
 };

 });

when i call this route from postman,i use form-data format in body.i got following response :

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

Guide me how can i use uploadMultipleFile function in route /add ?.

解决方案

You can use multer as middleware when you define your file Uploading router like this

In router file

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
});

Now go to your controller (uploadMultipleFile(req, res)) file.

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;
}

这篇关于在 node.js 中使用 multer 上传多个文件的服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆