晚上好
我在React功能组件中使用了Material-ui卡,并带有CardMedia:
<CardMedia
className={classes.media}
image={props.image}
title={props.cardTitle}
/>
我正在尝试确定图像文件的大小(以字节为单位)。经过一些研究,我找到了使用XMLHttpRequest的解决方案。重新下载文件对我来说似乎很奇怪。 我发现了如何使用:
获取图像的宽度和高度function checkImage() {
var img = new Image();
img.addEventListener("load", function(){
console.log( this.naturalWidth +' '+ this.naturalHeight );
});
img.src = props.image;
}
它可以工作,但这不是我想要的,如果我没有记错的话,它将再次下载图像。我查看了Mozilla文档,Image
仅具有width和height属性。由于图像已经加载,我应该有一种方法可以确定其大小(以字节为单位),而无需使用XMLHttpRequest吗?
答案 0 :(得分:4)
#1:
您可以使用Content-Length
请求来获取资源的HEAD
标头,如下所示:
fetch('https://your-domain/your-resource', { method: 'HEAD' })
.then(r => console.log('size:', r.headers.get('Content-Length'), 'bytes'));
这样,仅下载标题,仅此而已。
#2:或者,您也可以使用Resource Timing API:
const res = performance.getEntriesByName('https://your-domain/your-resource');
console.log(res[0].transferSize, res[0].encodedBodySize, res[0].decodedBodySize);
请注意,资源必须位于相同的子域中,否则您将不得不添加一个Timing-Allow-Origin
CORS标头。
#3:另一种选择是将图像下载为Blob:
fetch('https://your-domain/your-resource')
.then(r => r.blob())
.then(b => console.log(b.size, URL.createObjectURL(b)));
如果在初始加载后调用该图像,当然可以重新下载该图像,但是如果使用此方法进行初始加载,则可以使用对象URL来引用图像。