使用Multer更改上传文件的目的地

时间:2016-03-14 12:32:10

标签: javascript node.js multer

我正在使用Multer上传一些文件,我想将文件上传到不同的文件夹,具体取决于哪些用户上传文件。

这是我的代码:

server.js

app.use('/', require('./routes'));
app.use(express.static('public'));

路由/ index.js

var teacher = require('./teachers.js');

router.post('/teachers/{id}/upload', teacher.uploadAvatar);

路由/ teachers.js

var multer      = require('multer');
var upload      = multer({ dest: 'public/uploads/teacher/' }).single('avatar');

uploadAvatar: function(req, res) {
    upload(req, res, function(err) {
        console.log(req.body);
        console.log(req.file);

        if(err) {
            return res.end("Error uploading file.");
        }
        res.end("File is uploaded");
    });
}

文件上传完全正常,但我想为每个用户创建单独的文件夹。文件夹名称应为用户的ID。我可以像这样访问用户的ID:

teacherId: req.params.id

理想情况下,我还计划重命名上传的文件。

3 个答案:

答案 0 :(得分:2)

var multer  = require('multer')
var mkdirp = require('mkdirp');
uploadAvatar: function(req, res) {

mkdirp('public/uploads/' + req.params.id , function(err) { 
var upload      = multer({ dest: 'public/uploads/' + req.params.id }).single('avatar');
upload(req, res, function(err) {
    console.log(req.body);
    console.log(req.file);

    if(err) {
        return res.end("Error uploading file.");
    }
    res.end("File is uploaded");
});

});
}

那应该有用

答案 1 :(得分:0)

据我所知,您无法动态更改目的地。您可以在文件更新后移动它们。请在github上找到以下问题和答案,

https://github.com/expressjs/multer/issues/39

答案 2 :(得分:0)

您可以使用 express 路由器并在每个路由中初始化新的上传实例并将其用作中间件,例如:

const createPost = require('./routes/createPost');

app.use('/create-post', createPost);

然后在 routes/createPost.js 中:

const express = require('express');
const router = express.Router();
const multer = require('multer');

const upload = multer({ dest: 'uploads/new_destination' });

router.post('/', upload.single('imageToPost'), async(req, res) => {
    res.sendStatus(201);
});

module.exports = router;