使用 fetch API 请求 blob 图像并转换为 base64

2022-01-20 00:00:00 blob base64 fetch javascript fetch-api

我有一些图像将显示在 React 应用程序中.我向服务器执行 GET 请求,该服务器返回 BLOB 格式的图像.然后我将这些图像转换为 base64.最后,我将这些 base64 字符串设置在图像标签的 src 属性中.

I have some images that will be displayed in a React app. I perform a GET request to a server, which returns images in BLOB format. Then I transform these images to base64. Finally, i'm setting these base64 strings inside the src attribute of an image tag.

最近我开始使用 Fetch API.我想知道是否有办法在一次"中进行转换.

Recently I've started using the Fetch API. I was wondering if there is a way to do the transforming in 'one' go.

下面是一个例子来解释我到目前为止的想法和/或如果这甚至可以通过 Fetch API 实现.我还没有在网上找到任何东西.

Below an example to explain my idea so far and/or if this is even possible with the Fetch API. I haven't found anything online yet.

  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
  })

推荐答案

FileReader.readAsDataURL 的返回不是promise.您必须按照旧方式进行操作.

The return of FileReader.readAsDataURL is not a promise. You have to do it the old way.

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) ;

相关文章