在multer中将文件动态上传到项目特定目录

Pun*_*nit 1 node.js express meanjs multer

我正在尝试在 MEAN.js 应用程序中添加文件上传功能。我使用了multer,但它将所有文件直接放在初始化multer时指定的目的地。我想将文件上传到特定于要上传的程序的目录(当然,如果目录不存在,则动态创建目录)。我应该在哪里指定动态创建目录并将文件放入其中的自定义逻辑。

小智 5

我尝试了很多解决方案,但没有任何帮助。最后我写了这个,它有效!


我的解决方案(我使用 express 4.13 和 multer 1.2):

进口

var express = require('express');
var router = express.Router();
var fs = require('fs');
var multer  = require('multer');
Run Code Online (Sandbox Code Playgroud)


存储变量(请参阅此处的文档)

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


初始化 Multer:

var upload = multer(
    { 
        dest: 'uploads/',
        limits: {
            fieldNameSize: 100,
            fileSize: 60000000
        },
        storage: storage
    }
);
Run Code Online (Sandbox Code Playgroud)


使用它!

router.use("/upload", upload.single("obj"));
router.post('/upload', controllers.upload_file);
Run Code Online (Sandbox Code Playgroud)