multer - req.file always undefined
In case of postman, try following:
- Close the postman tab for the API
- Open a new tab again
- Rebuild the API request and then send.
This may fix the problem. Every time you restart the server you need to do above steps for calling the API again. The reason being multer sends back some cookies called connect.sid to the client which it may require in further communication. Using old cookies will not upload the file.
Your enctype
is slightly incorrect, it should be multipart/form-data
instead of multipart/formdata
.
I put MY (there are many I imagine and surely better) solution to help many people like me because I have searched during 1 entire day ;-(
//JS file on node sidevar express = require('express');var fileUpload = require('express-fileupload');var fs = require("fs");var app = express();console.log('étape 0');app.use(express.static('mesStatic'));app.use(fileUpload());console.log('étape 1');app.get('/indexFileUpload.htm', function (req, res) { res.sendFile( __dirname + "/" + "indexFileUpload.htm" );})console.log('étape 2');app.post('/file_upload', function (req, res) { console.log('étape 3'); console.log('req.files:' , req.files); if (!req.files) { res.send('No files to upload.'); return; } console.log('req.files.file.data:' , req.files.file.data); var bufDataFile = new Buffer(req.files.file.data, "utf-8"); console.log('étape 3.1'); console.log('__dirname : ' + __dirname); fs.writeFile(__dirname + '/file_upload/output.txt', bufDataFile, function(err) { if (err) { return console.error(err); } else { console.log("Data written successfully !"); } console.log('étape 4'); res.end('Fin OK !!!'); })})var server = app.listen(8081, function () { var host = server.address().address var port = server.address().port console.log("Example app listening at http://%s:%s", host, port);})