I am currently building a feature to upload a profile picture of the user, frontend is done and working however the backend keeps rejecting the image uploaded, even if it is a jpeg, jpg, png file type.
const storage = multer.memoryStorage();
const upload = multer({
storage: storage,
fileFilter: (req, file, cb) => {
const filetypes = /jpeg|jpg|png/;
const mimetype = filetypes.test(file.mimetype);
const extname = filetypes.test(path.extname(file.originalname).toLowerCase());
if (mimetype && extname) {
return cb(null, true);
}
cb(new Error('Invalid file type. Only JPEG and PNG files are allowed.'));
}
});
// Profile image upload endpoint
router.post('/upload-profile-image', upload.single('profile_img'), async (req, res) => {
const { customer_id } = req.query;
console.log('Upload request received for customer ID:', customer_id);
if (!req.file) {
console.log('No file uploaded.');
return res.status(400).send({ error: 'No file uploaded.' });
}
// Log file details
console.log('File received:', req.file.originalname, 'Size:', req.file.size);
console.log('MIME type:', req.file.mimetype);
try {
if (!req.file.buffer || req.file.buffer.length === 0) {
return res.status(400).send({ error: 'Uploaded file is empty.' });
}
console.log('Buffer length:', req.file.buffer.length);
console.log('Processing image...');
let processedImage;
if (req.file.mimetype === 'image/png') {
processedImage = await sharp(req.file.buffer)
.resize(150, 150)
.png({ quality: 80 })
.toBuffer();
} else if (req.file.mimetype === 'image/jpeg' || req.file.mimetype === 'image/jpg') {
processedImage = await sharp(req.file.buffer)
.resize(150, 150)
.jpeg({ quality: 80 })
.toBuffer();
} else {
return res.status(400).send({ error: 'Unsupported image format.' });
}
// Log successful image processing
console.log('Image processing complete. Compressed image size:', processedImage.length);
if (!Buffer.isBuffer(processedImage)) {
throw new Error('Processed image is not a valid buffer.');
}
const sql = 'UPDATE users SET profile_img = ? WHERE customer_id = ?';
console.log('Executing SQL query:', sql);
db.query(sql, [processedImage, customer_id], (err, result) => {
if (err) {
console.error('Database update failed:', err);
return res.status(500).send({ error: 'Database update failed.' });
}
console.log('Profile image updated successfully for customer ID:', customer_id);
res.status(200).send({ message: 'Profile image updated successfully.' });
});
} catch (error) {
console.error('Failed to process image:', error.message);
if (error.message.includes('Input buffer contains unsupported image format')) {
return res.status(400).send({ error: 'Input buffer contains unsupported image format.' });
}
res.status(500).send({ error: 'Failed to process image.' });
}
});
This is what I normally get in my backend logs:
I need help fixing the error:
Upload request received for customer ID: 2
File received: profile-image.jpg Size: 63
MIME type: image/jpeg
Buffer length: 63
Processing image...
Failed to process image: Input buffer contains unsupported image format
Error: Input buffer contains unsupported image format
at Sharp.toBuffer (C:UsersuserDocumentsPortfoliobackendnode_modulessharpliboutput.js:163:17)
at C:UsersuserDocumentsPortfolioustpEccomSystembackendroutescustomerData.js:59:18
at Layer.handle [as handle_request] (C:UsersuserDocumentsPortfoliobackendnode_modulesexpresslibrouterlayer.js:95:5)
at next (C:UsersuserDocumentsPortfoliobackendnode_modulesexpresslibrouterroute.js:149:13)
at done (C:UsersuserDocumentsPortfoliobackendnode_modulesmulterlibmake-middleware.js:45:7)
at indicateDone (C:UsersuserDocumentsPortfolio\backendnode_modulesmulterlibmake-middleware.js:49:68)
at Multipart.<anonymous> (C:UsersuserDocumentsPortfoliobackendnode_modulesmulterlibmake-middleware.js:166:7)
at Multipart.emit (node:events:514:28)
at emitCloseNT (node:internal/streams/destroy:132:10)
at process.processTicksAndRejections (node:internal/process/task_queues:81:21)
Failed to process image: Input buffer contains unsupported image format