Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retaining image file name and extension after upload in node.js (express) using multer

<!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.

like image 406
Murad Elboudy Avatar asked Feb 09 '23 00:02

Murad Elboudy


1 Answers

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)
like image 118
Krzysztof Sztompka Avatar answered Feb 11 '23 13:02

Krzysztof Sztompka