Get DataURL from Blob with await

331 Views Asked by At

I have fetch results that I want to turn into a typed DataURL.

I want to use await in the mainline of my app, not callbacks.

1

There are 1 best solutions below

0
Larry K On

function getDataUrlFromBlob

/* 
 * getDataUrlFromBlob
 * Optional: adds content type
 */
async function getDataUrlFromBlob(blob, contentType) {
    return new Promise((resolve, reject) => {
        let reader = new FileReader();
        reader.onload = (event) => {
            const data = event.target.result;
            resolve(data);
        };
        if (contentType) {
            blob = new Blob([blob], {type: contentType}); // add the type
        }
        reader.readAsDataURL(blob);
    });
}

Example usage

let response = await fetch(url, {method: "GET", mode: "cors"});
if (response && response.ok) {
    const contentType = response.headers.get('Content-Type');
    const blob = await response.blob();
    const dataUrl = await getDataUrlFromBlob(blob, contentType)
    return dataUrl;
}