Context: I am using an input type file to upload multiple images. Then I create a new object for each image to retrieve data: size, name, base64Url. Then I use Ajax to send list of object to controller, then I handle each image file in a loop to save image info to database(name, image path, Size). My problem is I couldn’t get all base64 value of list images. Before I can get base64 value of single image through a callback but come to a loop it didn’t fire event reader.onload for all item in loop, only the last item fire event.
2) I used blob url for preview images, but in Controller I tried Webclient.DownloadFile(url,path) it cannot download data from blob url, so I have to turn back to base64 value.
3) I also tried FormData, it can send all images data to IFromFile in controller, but for each image I want to add more information before sending to controller like ( productId, color, quantity,size).
That is all ways I tried, hope somebody help me solve my issues or give me another solution for sending multiple image to controller.
When i run my code below value of base64Val always = ' '. The callback below work fine for a single image but come to array of images, reader.onload will not fire.
$('#btn-start-upload').on('click', function () {
var listImgs = [];
for (var i = 0; i < image.imgData.length; i++) {
readImg(image.imgData[i], function (e) {
listImgs.push(e.target.result);
});
}
});
callback :
function readImg(file, onLoadCallback) {
var reader = new FileReader();
reader.onload = onLoadCallback;
reader.readAsDataURL(file);
},
I have tried debugging and see that reader is not completed before base64Val get value from reader.result or e.target.result, then 'listImgs' was empty or contained list of base64Val = ' '.
Update 2:
$('#btn-start-upload').on('click', function () {
let productId = $('#productId').val();
let listImgs = [];
image.readFileList(image.imgData).then((value) => {
listImgs.push(value);
});
});
function readFileList(files) {
return Promise.all(files.map(file => this.readFile(file))).then(contents => {
return contents;
});
},
function readFile(file) {
return new Promise(resolve => {
const fileReader = new FileReader();
fileReader.onload = () => resolve(fileReader.result);
fileReader.readAsText(file);
});
},