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

纵然是瞬间 提交于 2019-12-25 00:34:43

问题


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:

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

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


回答1:


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);
})



回答2:


You should make a unique name to save your file "generate a random string" and concat this this with the mimetype of your file. as you can see mimetype is already present in the req.file ,

function getFileExtension(mimeType){
if ( mimeType=== 'image/png') {
    return '.png';
}
else if ( mimeType=== 'image/jpg') {
    return '.jpg';
}
else if ( mimeType=== 'image/gif') {
    return '.gif';
}
else {
    return '.jpeg';
}
}

If you ae working on images this is the a utility function pass req.mimetype to this and concat its return value to your generated name



来源:https://stackoverflow.com/questions/58605335/multer-is-not-saving-the-file-as-the-same-name-and-without-extension

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