AJAX Post Request for Image File returning empty at the Express Route

Viewed 133

I believe there are few examples around the net for this however I was facing an issue related to my application. I have an input tag which accepts images. These images are then sent to a route using an AJAX POST Request which is where the issue arises. At the route when I console the req.body, it comes empty.

profile.hbs

<div class="wrapper">
                <input type="file" id="uploadfile" accept="image/png,image/jpeg,image/jpg" data-max-size="51200" />
</div>

profile.js

function readURL(input, img){
    if (input.files && input.files[0]) {

        if(input.files[0].size > 51200){
            return false;
        }

        let reader = new FileReader();

        reader.onload = function(e) {
            $(img).attr('src', e.target.result).show();
            imageRead = true;
        };
        reader.readAsDataURL(input.files[0]);

        let file = input.files[0];
        let fd = new FormData();
        fd.append("file", file);

        $.ajax({
            type: 'POST',
            url: '/profilePic',
            cache: false,
            contentType: false,
            processData: false,
            data: fd,
            success: function(data){console.log(data);},
            error: function(err){console.log(err);}
        });

    }
}
  $("#uploadfile").click().change(function(){
                readURL(this, '#profilePic');
            });

index.js

router.post('/profilePic', function(req, res, next){
    console.log(req.body); //This is returning empty
});
1 Answers

You can't check req.body for uploaded file information , use req.file or req.file.filename to get name of uploaded file

Related