Update
自从我发布原始答案以来,很多事情都发生了变化。
With multer 1.2.1
.
- 你需要使用
DiskStorage
指定where & how所存储的文件。
- 默认情况下,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
});