如何使用multer在nodejs中设置不同的目的地?

Aks*_*ayP 7 node.js multer

我正在尝试使用Multer包上传任何文件.当我在我的server.js文件中使用以下代码时它工作正常.

var express = require('express'),
    app = express(),
    multer = require('multer');
app.configure(function () {
    app.use(multer({
        dest: './static/uploads/',
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase();
        }
    }));
    app.use(express.static(__dirname + '/static'));
});

app.post('/api/upload', function (req, res) {
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

var server = app.listen(3000, function () {
    console.log('listening on port %d', server.address().port);
});
Run Code Online (Sandbox Code Playgroud)

我想要的是将文件存储在不同的位置.我曾尝试过代码,但它对我不起作用.

var express = require('express'),
    app = express(),
    multer = require('multer');
app.configure(function () {
    app.use(multer({
        //dest: './static/uploads/',
        rename: function (fieldname, filename) {
            return filename.replace(/\W+/g, '-').toLowerCase();
        }
    }));
    app.use(express.static(__dirname + '/static'));
});

app.post('/api/pdf', function (req, res) {
    app.use(multer({ dest: './static/pdf/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

app.post('/api/image', function (req, res) {
    app.use(multer({ dest: './static/image/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

app.post('/api/video', function (req, res) {
    app.use(multer({ dest: './static/video/'}));
    res.send({image: true, file: req.files.userFile.originalname, savedAs: req.files.userFile.name});
});

var server = app.listen(3000, function () {
    console.log('listening on port %d', server.address().port);
});
Run Code Online (Sandbox Code Playgroud)

意思是,如果我点击http://localhost:3000/api/pdf文件应该存储在'pdf'文件夹中,如果我点击http://localhost:3000/api/video文件应该存储在'video'文件夹中.

有没有办法实现这个目标?

先感谢您.

Sri*_*har 15

更新

自从我发布原始答案以来,有很多事情发生了变化.

随着multer 1.2.1.

  1. 您需要使用它DiskStorage来指定存储文件的位置方式.
  2. 默认情况下,multer将使用操作系统的默认目录.在我们的例子中,因为我们特别关注这个位置.在我们将文件保存到那里之前,我们需要确保该文件夹存在.

注意:在将目标作为函数提供时,您负责创建目录.

更多这里

'use strict';

let multer = require('multer');
let fs = require('fs-extra');

let upload = multer({
  storage: multer.diskStorage({
    destination: (req, file, callback) => {
      let type = req.params.type;
      let path = `./uploads/${type}`;
      fs.mkdirsSync(path);
      callback(null, path);
    },
    filename: (req, file, callback) => {
      //originalname is the uploaded file's name with extn
      callback(null, file.originalname);
    }
  })
});

app.post('/api/:type', upload.single('file'), (req, res) => {
  res.status(200).send();
});
Run Code Online (Sandbox Code Playgroud)

fs-extra用于创建目录,以防万一它不存在

原始答案

您可以使用changeDest.

用于重命名放置上载文件的目录的功能.

它从v0.1.8开始提供

app.post('/api/:type', multer({
dest: './uploads/',
changeDest: function(dest, req, res) {
    var newDestination = dest + req.params.type;
    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 + '"');
    }
    return newDestination
}
}), function(req, res) {
     //set your response
});
Run Code Online (Sandbox Code Playgroud)


小智 8

Multer是一个中间件,所以你可以像这样传递它:

app.post('/test/route', multer({...options...}), module.someThing)
Run Code Online (Sandbox Code Playgroud)

要么

app.post('/test/route', multer({...options...}), function(req, res){
........some code ......
});
Run Code Online (Sandbox Code Playgroud)