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

落爺英雄遲暮 提交于 2019-12-10 15:56:24

问题


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


回答1:


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)


来源:https://stackoverflow.com/questions/32654578/retaining-image-file-name-and-extension-after-upload-in-node-js-express-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!