Saving image file name and extension after loading 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>
Run codeHide result
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 loads an image using the multer module. But when the file is downloaded, it generates some sort of random name and even gets rid of the file extension. It just says β€œfile”. So how can I save the image name with extension.

+4
source share
1 answer

when you upload a file (using the multer.single method), you get the file data in

req.file

, originalname, mimetype, path . : https://github.com/expressjs/multer

mimetype.

?

a) , req.file( )

b) (req.file) db

:   , , - . , , .

: ( , ) ..

ok, ? - fs https://nodejs.org/api/fs.html :

fs.rename(oldPath, newPath, callback)

fs.renameSync(oldPath, newPath)
+8

Source: https://habr.com/ru/post/1608034/


All Articles