Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multer is not saving the file as the same name and without extension?

I am using Multer to save files I upload through a form but I do not know why my code saves it as a weird name and without extension and I have just used the code from the documentation.

server.js:

const multer  = require('multer');
const app = express();
var upload = multer({ dest: 'uploads/' })

app.post('/file', upload.single('filesToAttach'), function (req, res, next) {
    console.log(req.file);
    loadUserPage(req, res);
})

userPage.ejs:

<form action="/file" method="post" enctype="multipart/form-data">
    <div id="frm-attachments">
        <div>
            <h3>Attachments</h3>
            <div>
                <input type="file" id="attachFiles" name="filesToAttach" />
                <input type="submit" value="Attach">
            </div>
            <div id="frm-attach-files">
                Attached files
                <div>
                    <textarea id="field-attached-files" class="large-textbox" name="attached-files" spellcheck="true" rows="10" cols="50" tabindex="4" disabled="true"></textarea>
                </div>
            </div>
        </div>
    </div>
</form>

When I click on the submit button, a new file appear in the folder uploads which is supposed to have the same name and same extension as the file I uploaded in the form, but it has this name instead:

enter image description here

And if I try to print out(req.file), I see this:

enter image description here

Why is this happening? I do not even understand why they write the wrong code in the documentation...


1 Answers

You can set it externally,

Try this,

const multer  = require('multer');
const app = express();
var storage = multer.diskStorage({
  destination: 'uploads/',
  filename: function(req, file, callback) {
    callback(null, file.originalname);
  }
});
var upload = multer({ storage: storage })

app.post('/file', upload.single('filesToAttach'), function (req, res, next) {
    console.log(req.file);
    loadUserPage(req, res);
})
like image 181
Purushoth.Kesav Avatar answered Dec 02 '25 22:12

Purushoth.Kesav