I was struggling with a file upload I want to save via a PUT request. I updated the question with the solution.
I have a form that allows for multiple images to be uploaded in different fields, but also other fields with strings:
I loop over all fields in order to collect the information in a JSON, then push them towards my API:
keys is a dict with the names of the keys for the JSON (API checks for those keys), for example: name|STR
, price|FLOAT
, ppic|IMG
.
$('#checkButton').on('click', function( event ) {
let form = document.querySelector('#productForm');
let nbr = document.querySelector('#productdata').getAttribute("pid")
let return_dict = {"number": nbr};
const pendings = ["name", "pic"].map(async function ( key ) {
return_dict["name"] = form.elements[0].value;
return_dict["pic"] = await img_2_b64(form.elements[1]);
});
Promise.all(pendings).then((values) => {
write_2_DB_with_ajax_call ( return_dict )
});
});
If the key identifies the field as IMG I want to convert it to base64 and save it - this is my solution:
function img_2_b64( element ) {
return new Promise((resolve, reject) => {
let file = element.files[0];
let reader = new FileReader();
reader.onloadend = function(e) {
resolve(e.target.result);
};
reader.onerror = function() {
reject();
};
reader.readAsDataURL(file);
});