我正在尝试在进行 JavaScript 调用后获取要在 React 应用程序中显示的图像(PNG 格式)。代码如下。功能设备服务.getFile以 blob 形式返回文件。数据是二进制的。如何才能让这张图片在 React 中正确显示?
我尝试过转换为 Base64 但没有帮助。
DeviceService.getFile(mapOverlayImagePath, bMap1 => {
this.setState({ MapOverlay: bMap1 })
// this.setState({ MapOverlay: 'data:image/png;base64,' + btoa(bMap1) })
console.log(bMap1)
})
显示图像的 React 代码:
<img src={this.state.MapOverlay} alt="MapOverlay" />
我修改了这个功能,getFile函数如下:
export function getFile(path, cb) {
if (typeof(cb) === 'undefined' || cb === null)
return;
fetch(uris.getFile() + '/?' +
'path=' + path,
{method: 'POST', credentials: 'include'})
.then(reply => reply.blob())
.then((response) => {
if (response.data) {
return cb(response.data);
}
return cb(new Blob());
})
}
这个 getFile 函数位于一个库中,在 React 应用程序中用作依赖项。
我尝试在 Internet Explorer 控制台中打印 blob 大小,结果显示:[object Blob]: {size: 0, type: ""}
。我猜我的 getFile 函数没有按预期传递数据。 getFile 函数有错误吗?
将此 ArrayBuffer 制作为一个 Blob,并通过 blob-URI 使您的图像指向此 Blob。
fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png' )
.then( r => r.arrayBuffer() )
.then( buffer => { // note this is already an ArrayBuffer
// there is no buffer.data here
const blob = new Blob( [ buffer ] );
const url = URL.createObjectURL( blob );
const img = document.getElementById( 'img' );
img.src = url;
// So the Blob can be Garbage Collected
img.onload = e => URL.revokeObjectURL( url );
// ... do something else with 'buffer'
} );
<img id="img">
但如果你并不真正需要 ArrayBuffer,那么让浏览器直接将 Response 作为 Blob 来消费:
fetch( 'https://upload.wikimedia.org/wikipedia/commons/4/47/PNG_transparency_demonstration_1.png' )
.then( r => r.blob() ) // consume as a Blob
.then( blob => {
const url = URL.createObjectURL( blob );
const img = document.getElementById( 'img' );
img.src = url;
// in case you don't need the blob anymore
img.onload = e => URL.revokeObjectURL( url );
} );
<img id="img">
但是,在你的立场上,我什至会尝试直接从你的网站发出一个简单的 GET 请求<img>
to uris.getFile() + '/?path=' + path
.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)