How to set different destinations in nodejs using multer?

后端 未结 5 1858
你的背包
你的背包 2021-01-31 22:11

I\'m trying to upload any file using Multer package. It\'s working fine when I use following code in my server.js file.

var express         


        
5条回答
  •  攒了一身酷
    2021-01-31 22:36

    I tried the solutions shown here but nothing helped me.

    ChangeDest attr is not available anymore (As Sridhar proposes in his answer)

    I want to share my solution (I am using express 4.13 and multer 1.2):

    Imports:

    var express = require('express');
    var router = express.Router();
    var fs = require('fs');
    var multer  = require('multer');
    


    Storage variable (see documentation here)

    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            var dest = 'uploads/' + req.params.type;
            var stat = null;
            try {
                stat = fs.statSync(dest);
            } catch (err) {
                fs.mkdirSync(dest);
            }
            if (stat && !stat.isDirectory()) {
                throw new Error('Directory cannot be created because an inode of a different type exists at "' + dest + '"');
            }       
            cb(null, dest);
        }
    });
    


    Initializing Multer:

    var upload = multer(
        { 
            dest: 'uploads/',
            storage: storage
        }
    );
    


    Using it!

    router.use("/api/:type", upload.single("obj"));
    router.post('/api/:type', controllers.upload_file);
    

提交回复
热议问题