Rename a file with multer is not working

2019-07-01 17:59发布

I'm trying to rename a file using multer. I want to rename the file uploaded to a .jpg Instead of the tutorial about multer, i'm calling the method rename in my route file. The file is well uploaded but I don't get why the function rename is not working. By the way, the word 'ici' doesn't appear into my console

router.post('/edit/saveEdit',multer({
rename : function(fieldname, filename, req, res) {
    console.log('ici');
    return req.body.infoUser.id
}}),
function(req,res){

// console.log(req.body);
// console.log(JSON.stringify(req.files));

var conf = JSON.parse(fs.readFileSync(file_user));
var user = req.body.infoUser;


//changement de nom de fichier
// console.log(req.files.uploadAvatar);

Thanks for answers/help Thibault

res.end('good');

3条回答
神经病院院长
2楼-- · 2019-07-01 18:16

It is working on my side, please check if that works for you as well.

app.post('/api/photo', function(req, res) {

upload(req,res,function(err) {
        if(err) {
            return res.end("Error uploading file.");
        }
        //console.log("Resopnse "+res);  e74e107b91f6ed71c70eabb2c2d87d6c
        res.end("File is uploaded .... "+Date.now());
    });

});
查看更多
该账号已被封号
3楼-- · 2019-07-01 18:36

try using multer first for performing the desired operation on file and then serving the request. example :

router.use(multer({ 
  dest: './path/to/folder',
    rename : function (fieldname, filename, req, res) {
       console.log('ici');
       return req.body.infoUser.id
    }
  }
)));

router.post('/edit/saveEdit', function(req, res){
    // Operations saveEdit is hit
});
查看更多
贼婆χ
4楼-- · 2019-07-01 18:37

It is working for me with the code as below:

    var multer  = require('multer')
    var storage = multer.diskStorage({
        destination: function (req, file, cb) {
            cb(null, 'public/uploads/')
        },
        filename: function (req, file, cb) {

            var getFileExt = function(fileName){
                var fileExt = fileName.split(".");
                if( fileExt.length === 1 || ( fileExt[0] === "" && fileExt.length === 2 ) ) {
                    return "";
                }
                return fileExt.pop();
            }
            cb(null, Date.now() + '.' + getFileExt(file.originalname))
        }
    })

    var multerUpload = multer({ storage: storage })
    var uploadFile = multerUpload.single('file');
查看更多
登录 后发表回答