I had a problem when uploading an image to azure blob storage so after speding quite a bit of time on this I came out with this solution. It has logic for pc and android/ios separated as they work differently. Please take a look at the code below.
send to blob storage
if (Capacitor.platform === 'ios' || Capacitor.platform === 'android') {
const blob = this.base64ToBlob(file);
const fileToUpload = blob;
const xhr = new XMLHttpRequest();
xhr.open('PUT', path);
xhr.onload = () => {
console.log('sent to azure blob storage');
};
xhr.setRequestHeader('x-ms-blob-type', 'BlockBlob');
xhr.setRequestHeader('Content-Type', 'image/jpeg');
xhr.send(fileToUpload);
} else { // PC
this.http.put(path, file, {
headers: new HttpHeaders({
'x-ms-blob-type': 'BlockBlob',
'Content-Type': 'image/jpeg',
'x-ms-blob-content-type': file.type,
'X-Skip-Interceptor': ''
})
}).subscribe(() => {
console.log(`APP: ${fileName} uploaded to blob storage`);
});
}
base64ToBlob function
-> https://stackoverflow.com/a/16245768/5232022
base64ToBlob(file) {
let b64Data = file.base64Image;
const contentType = 'image/jpeg';
const sliceSize = 512;
b64Data = b64Data.replace(/data\:image\/(jpeg|jpg|png)\;base64\,/gi, '');
const byteCharacters = atob(b64Data); // decode base64
const byteArrays = [];
for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
const slice = byteCharacters.slice(offset, offset + sliceSize);
const byteNumbers = new Array(slice.length);
for (let i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
const byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
const blob = new Blob(byteArrays, { type: contentType });
return blob;
}