찾다

 >  Q&A  >  본문

node.js - 使用 express 中的multer上传文件, 上传的文件没有后缀名如何解决?

使用 express 中的multer上传文件, 上传的文件没有后缀名

var uploadZoneFile = upload.fields([{
                                        name: 'uploadLittleimg',
                                        maxCount: 1
                                    }, {
                                        name: 'uploadImg',
                                        maxCount: 1
                                    }, {
                                        name: 'uploadVoice',
                                        maxCount: 1
                                    }]);

router.post('/addZone', uploadZoneFile, function(req, res, next){


    console.log(req.files)

    var _uploadLittleimg = req.files.uploadLittleimg;
    var _uploadImg = req.files.uploadImg;
    var _uploadVoice = req.files.uploadVoice;

    if(_uploadLittleimg) req.body.littleimg = "/uploads/" + _uploadLittleimg[0].filename;
    if(_uploadImg) req.body.img = "/uploads/" + _uploadImg[0].filename;
    if(_uploadVoice) req.body.voice = "/uploads/" + _uploadVoice[0].filename;
    next();

}
...

其中有 filename 和 mimetype, 如何把文件后缀名加上去?
去官网看了没有参数做这种操作,
看源码我也很费力, 我还是新手, 求大神指点 谢谢

PHP中文网PHP中文网2785일 전631

모든 응답(1)나는 대답할 것이다

  • 怪我咯

    怪我咯2017-04-17 13:58:57

    那你就不能再用upload.fields了,你得用diskStorage,代码类似:

    var storage = multer.diskStorage({
      destination: function (req, file, cb) {
        cb(null, '/uploads');
      },
      filename: function (req, file, cb) {
        cb(null, file.fieldname + '.自己在这配置后缀名吧');
      }
    })
    
    var upload = multer({ storage: storage })
    
    router.post('/addZone', upload, function(req, res, next){
    
    
        console.log(req.files)
    
        var _uploadLittleimg = req.files.uploadLittleimg;
        var _uploadImg = req.files.uploadImg;
        var _uploadVoice = req.files.uploadVoice;
    
        if(_uploadLittleimg) req.body.littleimg = "/uploads/" + _uploadLittleimg[0].filename;
        if(_uploadImg) req.body.img = "/uploads/" + _uploadImg[0].filename;
        if(_uploadVoice) req.body.voice = "/uploads/" + _uploadVoice[0].filename;
        next();
    
    }

    회신하다
    0
  • 취소회신하다