I'm using AJAX to send an array of images to a server, and write them on the server side.
I want this to be as efficiant as possible, and I'm pretty sure that what I'm doing now is bad:
string[] is not efficiant.JSON.stringify to stringify the image data is a bad idea.Convert.FromBase64String on the server side is not efficiant.Here is my client side code:
This captures the image from a canvas element and add it to an array:
ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
imagesArr.push(canvas.toDataURL('image/jpeg', JPEG_QUALITY).replace('data:image/jpeg;base64,', ''))
This sends the images array to the server:
function sendImageBlock() {
$.ajax({
type: "POST",
url: "/AJAXServices.aspx/Upload",
data: JSON.stringify({images: imagesArr }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {},
error: function (xhr, status, message) {}
});
}
Here is my server side code:
[WebMethod]
public static int Upload(string[] images)
{
int index = 0;
foreach (string image in images)
{
File.WriteAllBytes(string.Format("{0}.jpeg", index.ToString(), Convert.FromBase64String(image));
index++;
}
}
Any suggestions how can I keep this clean and efficiant? Get rid of using the string formatting and use Binary data purley?
You can use Uint32Array in conjunction with xhr2 (HTML5 XMLHttpRequest Level 2) to send your data in its original binary format.
XMLHttpRequest Level 2 introduces a slew of new capabilities which put an end to crazy hacks in our web apps; things like cross-origin requests, uploading progress events, and support for uploading/downloading binary data.
More Info: https://www.html5rocks.com/en/tutorials/file/xhr2/
(function ($) {
// fetch the canvas data buffer into an Uint32Array
var imageData = ctx.getImageData(0, 0, ctx.canvas.width, ctx.canvas.height);
var data= new Uint32Array(imageData.data.buffer);
$.ajax({
url: 'server_address',
type: 'POST',
contentType: 'image/png',
// set processData to false to prevent string converstion
processData: false,
data:data
});
})(jQuery);
The data from the blob can be read in PHP this way:
<php>
$data = file_get_contents('php://input');
</php>