<!doctype html>
<html>
<body>
<form action="/upload" method="POST" enctype="multipart/form-data">
<input type='file' name="image">
<br>
<input type="submit" value="submit">
</form>
</body>
</html>
var express = require('express');
var router = express.Router();
var multer = require('multer');
var upload = multer({ dest: 'uploads/',
filename: function (req, file, cb) {
cb(null, file.fieldname + '-' + Date.now())
} });
router.post('/upload', upload.single('image'), function(req, res){
res.send("Uploaded");
});
module.exports = router;
I have this basic code that uploads an image using the multer module. But when the file is uploaded it generates some random name and even gets rid of the file extension. It just says type 'file'. So how can I keep the image name with the extension.
when you upload file (using multer.single method), you get file data in
req.file
it is object which have in properties originalname, mimetype, path and others. Check docs for all : https://github.com/expressjs/multer
But dont trust mimetype.
How keep image name and extension?
a) rename uploaded file using data in req.file (dont like it)
b) store file data (req.file) in db
edit about rename: when all downloaded files goes to one directory, and you change names to orginal, there may be conflicts - there may exists files with same names. Therefore, when you choose that way mayby you should move files to separate directories.
Next thing: Orginal file names may have insulting words or non standard chars (i dont know if it may be security isue) or be very long etc.
ok, how to rename? we can use express package fs https://nodejs.org/api/fs.html and methods:
fs.rename(oldPath, newPath, callback)
or
fs.renameSync(oldPath, newPath)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With