Node.js和Multer - 在回调函数中处理上传文件的目的地(req,res)

Lig*_*low 6 javascript variables upload node.js multer

我是Node.js的新手,我最近遇到了一个非常简单的问题.

我正在使用名为multer的模块,因此用户可以上传图像.在我的网络应用程序中,所有用户都有一个唯一的ID,我希望上传的图像存储在一个基于其ID的目录中.

例:

.public/uploads/3454367856437534
Run Code Online (Sandbox Code Playgroud)

这是我的routes.js文件的一部分:

// load multer to handle image uploads
var multer  = require('multer');
var saveDir = multer({
  dest: './public/uploads/' + req.user._id, //error, we can not access this id from here
  onFileUploadStart: function (file) { 
  return utils.validateImage(file); //validates the image file type
  }
});

module.exports = function(app, passport) {

app.post('/', saveDir, function(req, res) {
                id     : req.user._id,  //here i can access the user id
    });
});

}
Run Code Online (Sandbox Code Playgroud)

我怎样才能访问

req.user._id 
Run Code Online (Sandbox Code Playgroud)

在...之外

function(req,res)
Run Code Online (Sandbox Code Playgroud)

所以我可以使用它与multer生成基于id的正确目录?

编辑这是我尝试过但没有用的东西:

module.exports = function(app, passport) {

app.post('/', function(req, res) {
    app.use(multer({
        dest: './public/uploads/' + req.user._id
    }));
});

}
Run Code Online (Sandbox Code Playgroud)

Sri*_*har 5

更新资料

自从我发布原始答案以来,很多事情已经改变。

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 userId = req.user._id;
      let path = `./public/uploads//${userId}`;
      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('/', upload.single('file'), (req, res) => {
  res.status(200).send();
});
Run Code Online (Sandbox Code Playgroud)

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

原始答案

您可以使用changeDest

重命名放置上传文件的目录的功能。

v0.1.8可用

app.post('/', multer({
dest: './public/uploads/',
changeDest: function(dest, req, res) {
    var newDestination = dest + req.user._id;
    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)