I\'m working on uploading a file to my app using the multer npm module.
The multer function I have defined is to allow a single file uploaded to the file system. Ev
I solve this issues looking for the name that I passed on my request
I was sending on body:
{thumbbail: <myimg>}
and I was expect to:
upload.single('thumbnail')
so, I fix the name that a send on request
This for the Api you could use
const express = require('express');
const bodyParser = require('body-parser');
const app = express();
var multer = require('multer');
const port = 8000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.listen(port, ()=>{
console.log('We are live on' + port);
});
var upload = multer({dest:'./upload/'});
app.post('/post', upload.single('file'), function(req, res) {
console.log(req.file);
res.send("file saved on server");
});
This also works fine used on Postman but the file doesn't comes with .jpg extension any Advice? As commented below
This is the default feature of multer if uploads file with no extension, however, provides you the the file object, using which you can update the extension of the file.
var filename = req.file.filename;
var mimetype = req.file.mimetype;
mimetype = mimetype.split("/");
var filetype = mimetype[1];
var old_file = configUploading.settings.rootPathTmp+filename;
var new_file = configUploading.settings.rootPathTmp+filename+'.'+filetype;
rname(old_file,new_file);
Different file name which posted as "recfile" at <input type="file" name='recfile' placeholder="Select file"/>
and received as "file" at upload.single('file')
Solution : make sure both sent and received file are similar upload.single('recfile')
The <NAME>
you use in multer's upload.single(<NAME>)
function must be the same as the one you use in <input type="file" name="<NAME>" ...>
.
So you need to change
var type = upload.single('file')
to
var type = upload.single('recfile')
in you app.js
Hope this helps.
A follow up to vincent's answer.
Not a direct answer to the question since the question is using a form.
For me, it wasn't the name of the input tag that was used, but the name when appending the file to the formData.
front end file
var formData = new FormData();
formData.append('<NAME>',this.new_attachments)
web service file:
app.post('/upload', upload.single('<NAME>'),...