encoding an image to base64 with Fetch API - hogehoge666/syno_moments_slider GitHub Wiki

  • There are two ways to do this

1. Using readAsDataURL

  • use response.blob()
  • it will return a resolved Promise with blob data
    return fetch(url, requestOptions)
        .then(response => response.blob());
  • reader.onload is executed when readAsDataURL is executed
  • reader.onload returns resolved Promise with Base64 data.
  • Base64 data starts with "data:image/jpeg;base64,"
    return new Promise((resolve, reject) => {
        const reader = new FileReader;
        reader.onerror = reject;
        reader.onload = () => {
            resolve(reader.result);
        };
        reader.readAsDataURL(blob);
    })
    .then((imgBase64) => {
        const output = `<image src="${imgBase64}" alt="">`;
        console.log(output);
    })
}

2. Using window.btoa

  • use response.arrayBuffer()
  • it will return a resolved Promise with a byte array
    return fetch(url, requestOptions)
        .then(response => response.arrayBuffer());
  • use window.btoa to convert
function createThumbnailView(buffer) {
    let binary = '';
    const bytes = [].slice.call(new Uint8Array(buffer));
    bytes.forEach((b) => binary += String.fromCharCode(b));
    const base64Img = window.btoa(binary);
    const output = `<img src="data:image/jpeg;base64,${base64Img}">`;	

Reference

https://gist.github.com/n1ru4l/dc99062577b746e0783410b1298ab897