<!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>
<!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.
Share Improve this question edited Sep 18, 2015 at 15:07 Alexandr Lazarev 12.9k4 gold badges39 silver badges47 bronze badges asked Sep 18, 2015 at 14:32 Murad ElboudyMurad Elboudy 4832 gold badges12 silver badges24 bronze badges 1-
FWIW you may not want to rely on file extensions for arbitrary user uploads. You might look into using a module like
mmmagic
that inspects the file content to determine file type. – mscdex Commented Sep 18, 2015 at 14:46
1 Answer
Reset to default 8when 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./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/api/fs.html and methods:
fs.rename(oldPath, newPath, callback)
or
fs.renameSync(oldPath, newPath)