使用 fetch 发起请求时,将 responsetype 设为 blob 或调用 response.blob() 即可获取 png 数据。拿到 blob 对象后,通过 url.createobjecturl() 生成临时 url 并赋值给 img.src 即可在页面中显示图片。

如何配置 fetch 以正确接收二进制流
默认情况下 fetch 返回的是文本响应,直接读取会导致乱码。必须显式调用 response.blob() 方法,该方法会将响应体解析为二进制大对象(Blob),确保 PNG 文件的字节流不被破坏。

const url = '/api/image';
fetch(url)
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.blob();
})
.then(myBlob => {
const objectURL = URL.createObjectURL(myBlob);
const img = document.createElement('img');
img.src = objectURL;
document.body.appendChild(img);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
上述代码首先检查响应状态,确保请求成功。接着调用 blob() 获取二进制数据。随后创建 img 元素,将生成的 Object URL 赋给 src 属性,最后添加到 DOM 中。注意 URL.createObjectURL 会在内存中保留引用,应在不再需要时调用 URL.revokeObjectURL() 释放资源。
立即学习“Java免费学习笔记(深入)”;
使用Atmosphere构建通过WebSocket、SSE、gRPC、WebTransport、MCP、A2A和AG-UI流传输的JVM代理网关,并带有治理钩子。
如何处理跨域或安全策略限制
当接口位于不同域名时,浏览器会实施 CORS 策略。服务器必须在响应头中设置 Access-Control-Allow-Origin。客户端的 fetch 请求默认不发送 Cookie,若需携带凭证,需设置 credentials: 'include'。此外,若后端返回的不是标准图片 MIME 类型,前端仍可通过 Blob 处理,但需注意浏览器对非标准类型的渲染支持。

const url = 'https://other-domain.com/api/image';
fetch(url, {
method: 'GET',
credentials: 'include', // 如果需要携带 Cookie
headers: {
'Accept': 'image/png'
}
})
.then(response => {
// 检查 Content-Type 是否为 image/png
const contentType = response.headers.get('content-type');
if (!contentType || !contentType.includes('image/png')) {
throw new Error('Expected PNG image, got different content type');
}
return response.blob();
})
.then(blob => {
const objectURL = URL.createObjectURL(blob);
const img = document.createElement('img');
img.src = objectURL;
img.onload = () => {
// 图片加载完成后可以释放 URL
URL.revokeObjectURL(objectURL);
};
document.body.appendChild(img);
});
此示例展示了带凭证的请求及内容类型校验。通过检查 Content-Type 头部,确保接收到的是预期的 PNG 数据。在 img.onload 回调中释放 Object URL,避免内存泄漏。这种处理方式适用于需要从远程服务动态获取图片的场景。
基于 response.blob() 返回的 Blob 对象大小问题
response.blob() 返回的 Blob 对象包含完整的 PNG 数据,其 size 属性即为文件字节数。若接口返回的数据过大,可能导致内存压力。此时可考虑分块下载或使用流式处理,但对于常规 PNG 图片,一次性加载至 Blob 是标准且高效的做法。Blob 对象的 type 属性通常由服务器 Content-Type 决定,若未指定,默认为 application/octet-stream。

















