Skip to content Skip to sidebar Skip to footer

Sending An Image And Json Data To Server Using Ajax Post Request?

I want to send an image the user selected from their machine along with form data all wrapped up in a JSON object and sent to server. I am using Node for the server. Is it possible

Solution 1:

The common ways I encountered are using the Base64 string approach: you encode your image into a Base64 string and set it as part of the JSON Object that you send over to your server.

Another approach seems to be using the Binary Data in JSON but I'd never tried this before so not much info from me.

Here's a code sample to do a Base64 encoding in Javascript. Specifically look for the method below

functiongetBase64Image(imgElem) {
// imgElem must be on the same server otherwise a cross-origin error will be thrown "SECURITY_ERR: DOM Exception 18"var canvas = document.createElement("canvas");
    canvas.width = imgElem.clientWidth;
    canvas.height = imgElem.clientHeight;
    var ctx = canvas.getContext("2d");
    ctx.drawImage(imgElem, 0, 0);
    var dataURL = canvas.toDataURL("image/png");
    return dataURL.replace(/^data:image\/(png|jpg);base64,/, "");
}

Solution 2:

There is a way to achieve this: use image data.

In Javascript, on client side, the FileReader will allow you to read binary image data, and get them into a base64 encoded string.

On client side:

var file = $('.file-upload > input')[0].files[0];

functionupload(file) {
  var reader = newFileReader();

  // when image data was read
  reader.onload = function(event) {
    // I usually remove the prefix to only keep data, but it depends on your servervar data = event.target.result.replace("data:"+ file.type +";base64,", '');

    // make here your ajax call
    $.ajax({
      url: 'and_so_on',
      json: {
        data: data
      }
    });

  // read data from file
  reader.readAsDataURL(file);

}

On server side, you will received base64 encoded image that you can easilly translate into binary with the Buffer constructor

var buffer = new Buffer(data, 'base64');

Be warned that FileReader is not supported by all browsers

Post a Comment for "Sending An Image And Json Data To Server Using Ajax Post Request?"