Search code examples
node.jspostjpegmulter

Format issue while uploading Jpg file with NodeJS Multer module


I'm using Multer to upload jpg file from Postman to a node.js back-end.

I assume the "upload" goes well because the image is located at the right place with the right name and the right size after the POST request

Unfortunately, when I try to open the image file it doesn't open as a jpg image even though the extension is .jpg I used checkFileType website and apparently, the file type becomes application/octet-stream after the upload.

I didn't specify any headers in the request.

Here is my Postman setup

Here is the response

Here is the code in the Node API side

var localWorkLocation = '/Users/noste/CarFixer/Pictures/';

exports.createBinary = function (req, res) {
        var location = localWorkLocation + req.params.platenumber;
        var storageOptions = multer.diskStorage({
                        destination: function (req, file, callback) {
                            mkdirp(location, err => callback(err, location));
                            callback(null, location);
                        },
                        filename: function (req, file, callback) {
                            //if (!file.originalname.match(/\.(jpg|jpeg|png)$/)) {
                            //        return callback(new Error('Only image files are allowed!'), false);
                            //}
                            callback(null, file.originalname);
                        },
        });
        var upload = multer({storage : storageOptions}).single('picture');

        upload(req, res, function(err){
            console.log(req.file);
            if(err) {
                return res.end(err.message);
            }

            res.send(req.file);
        });
};

I've tried to upload a .txt file and it's still readable after upload. Is there a place where I need to specify that I want to keep the jpg format ?


Solution

  • here's the storage configuration u need .. change the naming according to your code

     var path = require('path');
     var storage = multer.diskStorage({
                destination: function(req, file, callback) {
                    callback(null, './uploads');
                },
    
                filename: function(req, file, callback) {
                    var fname = file.fieldname + '-' + Date.now() + path.extname(file.originalname);
    
                    callback(null, fname);
    
                }
            });
    

    And here's another answer for multiple files upload