Convert blob to base64

后端 未结 9 2013
无人共我
无人共我 2020-11-22 13:12

This is a snippet for the code that I want to do Blob to Base64 string:

This commented part works and that when the URL generated by this i

9条回答
  •  长情又很酷
    2020-11-22 13:39

    There is a pure JavaSript way that is not depended on any stacks:

    const blobToBase64 = blob => {
      const reader = new FileReader();
      reader.readAsDataURL(blob);
      return new Promise(resolve => {
        reader.onloadend = () => {
          resolve(reader.result);
        };
      });
    };
    

    For using this helper function you should set a callback, example:

    blobToBase64(blobData).then(res => {
      // do what you wanna do
      console.log(res); // res is base64 now
    });
    

    I write this helper function for my problem on React Native project, I wanted to download an image and then store it as a cached image:

    fetch(imageAddressAsStringValue)
      .then(res => res.blob())
      .then(blobToBase64)
      .then(finalResult => { 
        storeOnMyLocalDatabase(finalResult);
      });
    

提交回复
热议问题