I'm using multer
in the backend:
const filefilter = (req, file, cb) => {
if (file.mimetype === 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png' || file.mimetype === 'image/webp') {
cb(null, true)
} else {
cb(null, false)
}
}
var upload = multer({ dest: 'public/uploads', fileFilter: filefilter, limits: { fieldSize: 10 * 1024 * 1024 } });
router.post("/uploadFile",
(req, res) => {
upload.single("myFile")(req, res, function (err) {
if (err) {
// An error occurred when uploading
console.log('Err: ', err);
return;
} else {
console.log('req.file: ', JSON.stringify(req.file));
console.log('req.files: ', JSON.stringify(req.files));
return;
}
});
res.send({'Success': 'File uploaded'});
});
When the endpoint is getting invoked using POSTMAN, then it's working fine (means the req.file
is containing the selected file). The output is:
The console output of the backend is:
req.file: {"fieldname":"myFile","originalname":"ronaldo.jpeg","encoding":"7bit","mimetype":"image/jpeg","destination":"public/uploads","filename":"44d2b324d2185b2a48d59a4b541b4dc3","path":"public/uploads/44d2b324d2185b2a48d59a4b541b4dc3","size":126154}
req.files: undefined
The Flutter (Dart) code sample to invoke the endpoint is:
var request = http.MultipartRequest('POST', Uri.parse('http://127.0.0.1:3000/uploadFile'));
request.files.add(await http.MultipartFile.fromPath('myFile', filePath));
http.StreamedResponse response = await request.send();
if (response.statusCode == 200) {
print(await response.stream.bytesToString());
}
else {
print(response.reasonPhrase);
}
In this case, the console output of the backend is:
req.file: undefined
req.files: undefined
NOTE:
I have tried explicitly setting the 'Content-Type'
, 'Accept'
and 'Content-Encoding'
as 'multipart/form-data'
in the headers while sending the request. But, that didn't workout too. Even tried using the Dio package, no success with that as well.
Any help or suggestion will be highly appreciated.