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

2023-12-30

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

我在用着multer上传图像的模块。 在我的网络应用程序中,所有用户都有一个唯一的 ID,我希望将上传的图像存储在根据他们的 ID 命名的目录中。

Example:

.public/uploads/3454367856437534

这是我的一部分routes.js file:

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

}

我怎样才能访问req.user._id回调之外的属性function(req, res), 所以我可以用它multer,根据id生成正确的目录?

EDIT这是我尝试过但没有成功的方法:

module.exports = function(app, passport) {

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

}

Update

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

With multer 1.2.1.

  1. 你需要使用DiskStorage指定where & how所存储的文件。
  2. 默认情况下,multer 将使用操作系统的默认目录。就我们而言,因为我们对位置很挑剔。我们需要确保该文件夹存在,然后才能将文件保存到那里。

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

More here https://github.com/expressjs/multer#diskstorage

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

fs-extra用于创建目录,以防万一它不存在 https://www.npmjs.com/package/fs-extra#mkdirsdir-callback

原答案

您可以使用更改目的地 https://github.com/expressjs/multer#changedestdest-req-res

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

它可以从v0.1.8 https://github.com/expressjs/multer/issues/58#issuecomment-75315556

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
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

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