File Reader无法读取Fetch URL获取的Blob?求问题原因分析
问题根源与解决办法
核心问题:mode: 'no-cors'导致的不透明Blob
当你用mode: 'no-cors'发起fetch请求时,浏览器会返回一个不透明(opaque)的Blob。这种Blob的内容被浏览器严格限制访问,你无法通过FileReader读取它的内容,自然没法生成DataURL赋值给img标签的src属性。
另外你把原jpg格式的Blob强制指定为image/png类型,属于类型不匹配,但这不是代码失效的主要原因——就算类型正确,不透明Blob依然无法被读取。
修正方案
方案1:移除mode: 'no-cors'(如果目标服务器支持CORS)
如果目标图片服务器允许跨域请求,直接去掉mode: 'no-cors'配置,这样fetch会返回正常响应,后续的Blob、File转换和FileReader读取流程就能正常工作:
<img id="imageDisplay" alt="Uploaded Image"> <script> async function fetchImageAndCreateFile() { try { // 移除mode: 'no-cors' const response = await fetch('https://e0.pxfuel.com/wallpapers/696/883/desktop-wallpaper-large-size-and-large-nature.jpg'); const blob = await response.blob(); // 使用原响应的content-type,避免硬写类型不匹配 const file = new File([blob], 'image.jpg', { type: response.headers.get('content-type') || 'image/jpeg' }); console.log(file); return file; } catch (error) { console.error('Error fetching image:', error); } } fetchImageAndCreateFile().then(file => { if (!file) return; const reader = new FileReader(); reader.onload = function(e) { document.getElementById('imageDisplay').src = e.target.result; }; reader.readAsDataURL(file); }).catch(error => { console.error('Error in main function:', error); }); </script>
方案2:直接赋值图片URL(最优写法)
你完全不需要绕fetch→Blob→File→FileReader这一大圈,直接把图片URL赋值给img的src属性是最简单高效的方式,还能避免跨域和Blob读取的问题:
<img id="imageDisplay" alt="Uploaded Image" src="https://e0.pxfuel.com/wallpapers/696/883/desktop-wallpaper-large-size-and-large-nature.jpg">
或者用JS动态赋值:
<img id="imageDisplay" alt="Uploaded Image"> <script> document.getElementById('imageDisplay').src = 'https://e0.pxfuel.com/wallpapers/696/883/desktop-wallpaper-large-size-and-large-nature.jpg'; </script>
内容的提问来源于stack exchange,提问作者Pedro Sturmer
相关产品推荐
相关产品推荐

