node multer返回新文件名

时间:2016-10-03 13:04:20

标签: node.js multer

如何让multer为上传的文件返回新文件名(superfilename)?

所以完成后,它会返回新的文件名吗?

服务器支持:

  var storage = multer.diskStorage({ //multers disk storage settings
    destination: function (req, file, cb) {
      cb(null, '/opt/mean/public/uploads/')
    },
    filename: function (req, file, cb) {
      var datetimestamp = Date.now();
      var superfilename = file.fieldname + '-' + datetimestamp + '.' + file.originalname.split('.')[file.originalname.split('.').length -1];
      cb(null, superfilename)
    }
  });
  var upload = multer({ //multer settings
    storage: storage
  }).single('file');



  upload(req,res,function(err){

          if(err){
            res.json({error_code:1,err_desc:err});
            return;
          }
          res.json({error_code:0,err_desc:null});
        });

1 个答案:

答案 0 :(得分:0)

您可以重新启动目标文件名:req.file.filename

一种方法是将上传对象作为上传路由的中间件传递,如下所示。 Rest文件相关信息将在您的请求对象中。您可以参考official documentation了解公开的api

app.post('/uploadFile',upload,(req,res)=>{

      if(req.file !==  undefined){

        // once uploaded save the user data along with uploaded photo path to the database.
        res.json({
           'fileName':req.file.originalname,
           'destination':req.file.filename,
           'userName':req.body.userName,
           'phoneNumer':req.body.phoneNumber
        });
      }else{
        res.json({
          'message':'Unable to Upload file'
        });
      }
  });