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?
-
sure it is possible, What code do you have so far? – Aras Feb 21 '14 at 06:35
2 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,/, "");
}

- 21,381
- 38
- 125
- 225

- 1,959
- 6
- 30
- 57
-
I'm using Python Flask framework, so how can i get the image back in python from the base64 string? – Aashish Kumar Feb 18 '18 at 05:24
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];
function upload(file) {
var reader = new FileReader();
// when image data was read
reader.onload = function(event) {
// I usually remove the prefix to only keep data, but it depends on your server
var 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

- 1,898
- 14
- 18
-
-
You can also use the [btoa()](https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/btoa) ([browser support](http://caniuse.com/#feat=atob-btoa)) function to create the base64 String (var data = btoa(event.target.result)), together with reader.readAsBinaryString(file). Then you don't need to do the String replacement. – Guno Heitman Jul 11 '16 at 09:37
-
-
I'm using Python Flask framework, so how can i get the image back in python from the base64 string? – Aashish Kumar Feb 18 '18 at 05:24