Des*_*eus 14 javascript base64 blob fetch fetch-api
我有一些图像将显示在 React 应用程序中。我向服务器执行 GET 请求,该请求以 BLOB 格式返回图像。然后我将这些图像转换为 base64。最后,我在图像标签的 src 属性中设置这些 base64 字符串。
最近我开始使用 Fetch API。我想知道是否有办法在“一次”中进行转换。
下面是一个示例来解释我目前的想法和/或 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
})
Run Code Online (Sandbox Code Playgroud)
Get*_*ree 19
的回报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) ;
}) ;
Run Code Online (Sandbox Code Playgroud)
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) ;
Run Code Online (Sandbox Code Playgroud)
Aug*_*ger 11
感谢@GetFree,这是async/await它的版本,带有承诺错误处理:
const imageUrlToBase64 = async url => {
const response = await fetch(url);
const blob = await response.blob();
return new Promise((onSuccess, onError) => {
try {
const reader = new FileReader() ;
reader.onload = function(){ onSuccess(this.result) } ;
reader.readAsDataURL(blob) ;
} catch(e) {
onError(e);
}
});
};
Run Code Online (Sandbox Code Playgroud)
用法:
const base64 = await imageUrlToBase64('https://via.placeholder.com/150');
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11590 次 |
| 最近记录: |