You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过API获取图片并使用FileReader()存入localStorage?

从JPEG API获取图片并存入localStorage的实现方案

要实现这个需求,核心是把API返回的JPEG图片转成base64格式的字符串(因为localStorage仅支持存储字符串类型数据),用FileReader处理Blob对象即可完成转换,具体步骤如下:

1. 请求API获取图片Blob并转存到localStorage

先通过请求获取API返回的图片Blob,再用FileReader将其转为Data URL(base64格式),最后存入localStorage:

// 替换为你的API地址
const imageApiUrl = 'https://example.com/api/image';

fetch(imageApiUrl)
  .then(res => {
    // 确保响应是成功的
    if (!res.ok) throw new Error(`请求失败,状态码:${res.status}`);
    return res.blob();
  })
  .then(blob => {
    const reader = new FileReader();
    // 读取完成后触发回调
    reader.onload = function(e) {
      // 将base64字符串存入localStorage,键名可自定义
      localStorage.setItem('storedJpegImage', e.target.result);
      console.log('图片已成功存入localStorage');
    };
    // 以Data URL格式读取Blob
    reader.readAsDataURL(blob);
  })
  .catch(err => console.error('处理过程出错:', err));

2. 从localStorage读取并显示图片

如果需要取出存储的图片,直接读取对应的字符串并赋值给图片元素的src即可:

const savedImage = localStorage.getItem('storedJpegImage');
if (savedImage) {
  const imgElement = document.createElement('img');
  imgElement.src = savedImage;
  // 将图片添加到页面中
  document.body.appendChild(imgElement);
}

常见问题说明

  • 你之前尝试File()失败的原因:File对象主要用于封装本地文件,远程API返回的资源直接用Blob处理即可,无需转成File类型。
  • 注意存储上限:localStorage的单域名存储上限通常在5MB左右,若图片过大可能无法存入,建议提前判断Blob大小。
  • 跨域问题:确保你的页面域名与API域名允许跨域请求,否则会出现CORS错误。

内容的提问来源于stack exchange,提问作者Rahman Sharifi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 21:35:14