Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 to place the image in the JSON object along with the other form elements and read in Node?

like image 841
Irlanco Avatar asked Feb 21 '14 06:02

Irlanco


People also ask

Can AJAX send data to server?

$. ajax() method allows you to send asynchronous http requests to submit or retrieve data from the server without reloading the whole page. $. ajax() can be used to send http GET, POST, PUT, DELETE etc.

Can I send image with JSON?

An image is of the type "binary" which is none of those. So you can't directly insert an image into JSON. What you can do is convert the image to a textual representation which can then be used as a normal string. The most common way to achieve that is with what's called base64.

Can AJAX send JSON?

According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page. Many developers use JSON to pass AJAX updates between the client and the server.

Can we upload image using AJAX?

jQuery AJAX image upload requires core jQuery features and nothing fancy is used. For AJAX image upload, enctype='multipart/form-data' is not required as we are not submitting via form post. We are using AJAX data transfer and multipart form data is not required for the image upload.


1 Answers

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

function getBase64Image(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,/, "");
}
like image 134
ipohfly Avatar answered Oct 24 '22 11:10

ipohfly