nodejs multer file upload, what happens file names

2019-12-16 19:45发布

问题:

The concept is still not clear to me yet. For a very basic case, i can upload a file (say myFile.txt) using multer, and keep its original name in the server side.

const upload = multer({ dest: `${UPLOAD_PATH}/` }); // multer configuration

Now another person happen to upload a different file with same file name myFile.txt to the same folder in server side. Will it overwrite the previous one ?

How do you normally manage this ? Thanks !

回答1:

Will it overwrite the previous one ?

Yes it will definitely replace with the new one.Here is my code .In this code if you use a same file name from different locations or from the same location it won't replaces.It keeps both the files in destination.Server code server.js

var express=require('express');
var multer=require('multer');
var path = require('path')
var app=express();
var ejs = require('ejs')
app.set('view engine', 'ejs')
var storage = multer.diskStorage({
    destination: function(req, file, callback) {
        callback(null, './public/uploads')
    },
    filename: function(req, file, callback) {
        callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname))
        //callback(null, file.originalname)
    }
})

app.get('/api/file',function(req,res){
res.render('index');
});
app.post('/api/file', function(req, res) {
    var upload = multer({
        storage: storage}).single('userFile');
    upload(req, res, function(err) {
        console.log("File uploaded");
        res.end('File is uploaded')
    })
})

app.listen(3000,function(){
console.log("working on port 3000");
});

If you observe the code callback(null, file.originalname) this line will keep the original file name in destination and will replace the file when it gets the same name.If you don't want this then use callback(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname)).This callback changes the name of file in destination.

Make a views folder and keep this file in it.ejs code from which you can choose a file to upload index.ejs

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<body>
    <form id="uploadForm" enctype="multipart/form-data" method="post">
        <input type="file" name="userFile" />
        <input type="submit" value="Upload File" name="submit">
    </form>
</body>
</html>

Run the code as node server.js.Open the browser and type http://localhost:3000/api/file.Choose a file to upload and see the destination folder.Hope this helps for you.



回答2:

actually Multer saves the file in a given path (as specied by you) but with a different randomised filename. It will not override the file even if the name of the file is the same. So your UPLOAD_PATH will have multiple files even if you are loading the the file with same name again.