我试图在进行JavaScript调用后获取要在React应用中显示的图像(PNG格式)。代码如下。函数DeviceService.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函数中有任何错误吗?
通过blob-URI,创建此ArrayBuffer的Blob,并使图像指向该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">
但是,在您的位置上,我什至尝试直接从<img>
to发送一个简单的GET请求uris.getFile() + '/?path=' + path
。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句