I need to send an object including a base64-encoded image to an API-endpoint in TS. I use this code to convert a file to Base64 and attach it to an object:
const file = values.beleg1;
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = async function () {
const result = reader.result.toString().split(',')[1];
await valuesObj.push({ name: 'base64Image', value: result });
};
reader.onerror = function (error) {
console.log('Error: ', error);
};
If I then log the object ‘valuesObj’ it does show that the base64-object is attached to the main-object.

However when I then I then use this object in the request like in the code below it is not shown in the payload when looking at the network-request
axios({
url: 'http://localhost:8080/createPDF',
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
responseType: 'blob',
data: valuesObj,
})
.then((response: AxiosResponse) => {
setLoadingText('');
const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
const objectUrl: string = window.URL.createObjectURL(blob);
window.open(objectUrl);
})
.catch((error) => {
console.log(error);
});
What is the reason for this? Does it have anything to do with the length/size of the string? Or is there another reason?
>Solution :
Your Problem seems to be that your async axios request gets the value of your valuesObj, before onload actually adds your new record.
Sorry forgot a solution ^^
Either you put your axios request directly into the pipe…
reader.onload =
(async function () {
const result = reader.result.toString().split(',')[1];
await valuesObj.push({ name: 'base64Image', value: result
return valuesObj
})
.then(
newValuesObj =>
axios({
url: 'http://localhost:8080/createPDF',
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
responseType: 'blob',
data: newValuesObj,
})
.then((response: AxiosResponse) => {
setLoadingText('');
const blob: Blob = new Blob([response.data], { type: 'application/pdf' });
const objectUrl: string = window.URL.createObjectURL(blob);
window.open(objectUrl);
})
.catch((error) => {
console.log(error);
})})
)
})
or you create another async function which you can call from your onload or from another async fn, which awaits both async events.
