ブロブ画像をリクエストし、フェッチAPIでbase64に変換する 質問する

ブロブ画像をリクエストし、フェッチAPIでbase64に変換する 質問する

React アプリに表示される画像がいくつかあります。サーバーに GET リクエストを実行すると、BLOB 形式で画像が返されます。次に、これらの画像を base64 に変換します。最後に、これらの base64 文字列を画像タグの src 属性内に設定します。

最近、Fetch API を使い始めました。変換を 1 回で実行する方法があるかどうか知りたいです。

以下は、これまでの私のアイデアと、これが Fetch API で可能かどうかを説明する例です。まだオンラインでは何も見つけていません。

  let reader = new window.FileReader();
  fetch('http://localhost:3000/whatever')
  .then(response => response.blob())
  .then(myBlob => reader.readAsDataURL(myBlob))
  .then(myBase64 => {
    imagesString = myBase64
  }).catch(error => {
    //Lalala
  })

ベストアンサー1

の返却はFileReader.readAsDataURL約束ではありません。従来の方法で行う必要があります。

fetch('http://localhost:3000/whatever')
.then( response => response.blob() )
.then( blob =>{
    var reader = new FileReader() ;
    reader.onload = function(){ console.log(this.result) } ; // <--- `this.result` contains a base64 data URI
    reader.readAsDataURL(blob) ;
}) ;

汎用機能:

function urlContentToDataUri(url){
    return  fetch(url)
            .then( response => response.blob() )
            .then( blob => new Promise( callback =>{
                let reader = new FileReader() ;
                reader.onload = function(){ callback(this.result) } ;
                reader.readAsDataURL(blob) ;
            }) ) ;
}

//Usage example:
urlContentToDataUri('http://example.com').then( dataUri => console.log(dataUri) ) ;

//Usage example using await:
let dataUri = await urlContentToDataUri('http://example.com') ;
console.log(dataUri) ;

おすすめ記事