How can I set uploaded file name?

2019-07-03 01:15发布

By using 'multer' , I made it to request image file like this. enter image description here

And this file is stored at 'uploads' folder I set. my code is below:

var multer  = require('multer')
var upload = multer({dest:'./uploads/'});
//var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
    console.log(req.file);
});

But I want to set my file name like 'abc.png' not 'abc'

I read docs and what I found is that

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/uploads');
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now());
  }
});

var upload = multer({ storage: storage });

So my modified code is below:

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

var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
    console.log(req.file);
});

But in this case, the error occurs and says 'Error: ENOENT, open '/uploads/puzzle-1449496743377' , not like the picture above...

How could I solve this?

I'm sure many newbie developers like me will have in trouble thanks to unkind docs...

2条回答
2楼-- · 2019-07-03 01:21

I think your problem is in the definition of the destination dir. The starting '.' is missing. Try to use this code:

destination: function (req, file, cb) {
  cb(null, './uploads/');
},
查看更多
Root(大扎)
3楼-- · 2019-07-03 01:22
    var fs = require('fs');
var multer  = require('multer')
//var uploader = multer({dest:'./uploads/'});

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, './uploads/')
  },
  filename: function (req, file, cb) {
    crypto.pseudoRandomBytes(16, function (err, raw) {
      cb(null, raw.toString('hex') + Date.now() + '.png');
    });
  }
});
var upload = multer({ storage: storage });
var app = express();
app.use(app.router);
app.post('/upload', upload.single('puzzle'), function (req, res, next) {
    console.log(req.file);
});

Solved, thank you all guys thank you

查看更多
登录 后发表回答