I was working on building rest API, Where I want to upload multiple images with one post request.
So here. I am trying to make an array of base64 string of selected images. That array is JSON.stringify(images_to_upload) to convert to string. and send that string as JSON post. and on server side use json_decode() to decode the string array and save the images.
Is my approach correct? i am not able to execute JSON.stringify(images_to_upload) as this returns nothing.
is there any better way to handle this?
JAVASCRIPT
$("#UploadImage").click(function(){
var filesSelected = document.getElementById("filesToUpload").files;
var images_to_upload = new Array();
//Loop through each image
for(var i=0;i<filesSelected.length;i++)
{
var fileToLoad = filesSelected[i];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
var img_string = fileLoadedEvent.target.result;
//push base64 string in arrray
images_to_upload.push(img_string);
};
fileReader.readAsDataURL(fileToLoad);
}
console.log(JSON.stringify(images_to_upload)); //this doesnt work
data = {
"images_data":JSON.stringify(images_to_upload) ,
};
url = "http://app.com/api/customer/uploadmultipleimg";
$.ajax({
type: "POST",
url: url,
data:data,
success: function(result){
console.log(result);
},
failure: function(errMsg) {
console.log(errMsg);
}
});
});
HTML
<input type="file" name="filesToUpload" id="filesToUpload" multiple="" accept="image/x-png,image/jpeg">
<input type="submit" value="UploadImage" id="UploadImage" name="submit">