Despite my best efforts, I am unable to get multer's file upload feature to work. Despite studying numerous tutorials and guides on YouTube, as well as diving into countless StackOverflow threads, I still struggle to make it function properly through Postman.
This issue pertains to the route /image-upload.
Below is the complete code snippet:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const passport = require('passport');
const bodyParser = require('body-parser');
const jwt = require('jsonwebtoken');
const multer = require('multer');
const fileUpload = require('express-fileupload');
let path = require('path');
var storage = multer.diskStorage({
destination: (req, file, cb) => {
cb(null, __dirname + '../uploads')
},
filename: (req, file, cb) => {
cb(null, file.fieldname + '-' + Date.now())
}
});
var upload = multer({storage: storage});
router.post('/', upload.single('image'), (req, res, next) => {
let file = req.file;
console.log(req.file);
console.log(req.files);
if (!file) {
return res.json({nofile: 'please upload a file'})
}
})
module.exports = router;
The size of the file being uploaded is not the problem, as it is only 46KB in size. Strangely, when I log `req.file`, it returns undefined. However, when I log `req.files`, I do receive the full data details. When using Postman with form-data correctly set up for the POST route, it simply returns a json error, almost as if multer is not recognizing or reading the file at all. In Postman, I am ensuring that I am using form-data for the POST request, and the field name for the file is set to 'image', matching what is specified in the POST route.