请求Blob图像并使用访存API转换为base64 [英] Requesting blob images and transforming to base64 with 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
的返回不是保证.您必须采用旧方法.
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) ;
}) ;
这篇关于请求Blob图像并使用访存API转换为base64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!