I am building an app in React and Node that has an upload component. I managed to upload the file in React sent it to node with multer but it gets saved as a random string without any termination, just of type file. If i manually change the termination to pdf to say I can open it and see the content but I would like to do that automatically.
Here is what I have done in nodejs:
var multer = require('multer')
const upload = multer({ dest: "./uploads" });
app.post('/upload', upload.single('file'), function (req, res, next) {
var f = req.file;
console.log(f);
var s = req.body.standard;
console.log(s);
})
On he file console log it prints me the details of the file. Of the things I have tried was to change
req.file.filename = req.file.originalname; req.file.path = "./uploads/"+req.file.originalname;
thinking that it might change the file name on the computer but it didn`t work.
Another thing that I have tried is to insert this code:
var storage = multer.diskStorage({
destination: function (req, file, cb) {
cb(null, 'public')
},
filename: function (req, file, cb) {
cb(null, Date.now() + '-' +file.originalname )
}
})
and modify const upload with var upload = multer({ storage: storage }).single('file')
outside the post method and inside it but it does not work. It does not do anything.
Can someone please provide me full code on how my js page sould look with the post method and the code that sets the filename and folder inside the node project. Thanks in advance. On the internet I can only find snippets of code and I do not know where to integrate them.
Thanks
Try bellow code
const multer = require('multer')
const storage = multer.diskStorage({
destination: function(req, file, cb) {
cb(null, 'public')
},
filename: function(req, file, cb) {
cb(null, Date.now() + '-' + file.originalname)
}
})
const upload = multer({
storage: storage
})
app.post('/upload', upload.single('file'), function(req, res, next) {
const f = req.file;
console.log(f);
const s = req.body.standard;
console.log(s);
})