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

如何解决JavaScript中input file图片存入localStorage后加载不显示问题

问题:本地存储的产品图片无法在页面加载时显示

我有一个input type="file"控件用于选择图片,搭配多个input type="text"收集产品数据,点击按钮后将数据存入localStorage。页面加载时,除productImg外其他数据都能正常显示,需要实现将产品图片存入localStorage并在页面加载时正确显示。

原HTML代码

<button id="adminSponsorPush" class="btn btn-lg btn-success " style="width: 30%;" onclick="text()">Sponsored Products</button>
<input type="file" id="adminDealImg">
<input type="text" name="" id="adminDealName" placeholder="Product Name">
<input type="text" name="" id="adminOldPrice" placeholder="deals Old Price">
<input type="text" name="" id="adminNewPrice" placeholder="deals new Price">
<button type="button" onclick="setIt()" class="btn btn-primary">Understood</button>
<div id="todaysDeal" class="d-flex flex-wrap w-100 gap-3 p-2 border border-danger border-2"></div>

问题原因

input type="file"的value属性返回的是浏览器安全处理后的伪路径(如C:\fakepath\xxx.jpg),这个路径无法被浏览器识别加载图片,因此需要将图片文件转换为Base64编码字符串存入localStorage,才能在页面加载时正常显示。

修改后的代码

1. 存储数据的JavaScript代码(更新图片存储逻辑)

let allProducts = [];
if (localStorage.companyProduct) {
  allProducts = JSON.parse(localStorage.getItem("companyProduct"));
}

text = () => {
  let products = {
    firstName: "",
    lastName: "",
    email: "",
    phoneNumber: "",
    password: "",
    topDeal: [],
    sponsorProduct: [],
    recommendedProduct: [],
    inspiredProduct: [],
    laptops: [],
    smartPhone: [],
    healthBeauty: [],
    groceries: [],
    videoGames: [],
    mobileAccessories: [],
    homeFurnishings: [],
    fitnessToolsEquipment: [],
    kidsWearAccessories: [],
    topDealOnTelevision: [],
  };

  allProducts.push(products);
  localStorage.setItem("companyProduct", JSON.stringify(allProducts));
};

// 图片转Base64工具函数
function convertToBase64(file, callback) {
  const reader = new FileReader();
  reader.onload = function(e) {
    callback(e.target.result);
  };
  reader.readAsDataURL(file);
}

setIt = () => {
  const fileInput = document.getElementById("adminDealImg");
  // 检查是否选择了图片
  if (!fileInput.files || fileInput.files.length === 0) {
    alert("请先选择产品图片");
    return;
  }

  // 转成Base64后再存储
  convertToBase64(fileInput.files[0], (base64Img) => {
    for (let index = 0; index < allProducts.length; index++) {
      let topDealProduct = {
        productImg: base64Img, // 存储Base64格式图片
        productName: adminDealName.value,
        productOldPrice: adminOldPrice.value,
        productCategory: `product`,
        productNewPrice: adminNewPrice.value,
        productSavePrice: `You save ₦${adminOldPrice.value - adminNewPrice.value}`,
      };
      allProducts[index].topDeal.push(topDealProduct);
      localStorage.setItem("companyProduct", JSON.stringify(allProducts));
      localStorage.setItem("currentUserIndex", index);
    }
    // 清空输入框,避免重复提交
    fileInput.value = "";
    adminDealName.value = "";
    adminOldPrice.value = "";
    adminNewPrice.value = "";
    // 实时更新页面显示
    displayProducts();
  });
};

2. 页面加载显示的JavaScript代码

currentProductIndex = localStorage.getItem("currentUserIndex");

displayProducts = () => {
  todaysDeal.innerHTML = "";
  eachTopDealProduct = allProducts[currentProductIndex].topDeal;
  for (let index = 0; index < eachTopDealProduct.length; index++) {
    todaysDeal.innerHTML += `
  <div onclick="topDealProductPage(${index})" class="d-flex p-3 shadow each-todays-deal gap-3"
  style="width: 32.5%; height: 120px; cursor: pointer;"
>
<img src="${eachTopDealProduct[index].productImg}" alt="产品图片" id="dealsImg"/>
  <div class="d-flex flex-column gap-3">
    <div class="text-capitalize" id="dealsProductName">${eachTopDealProduct[index].productName}</div>
    <div class="">
      <div class="d-flex gap-2">
      
      <div class="fw-bold fs-4" id="dealsPrice">₦${eachTopDealProduct[index].productNewPrice}</div>
      <div class="fw-bold fs-6 my-auto text-decoration-line-through text-secondary" id="dealsPrice">₦${eachTopDealProduct[index].productOldPrice}</div>
      </div>
      <div class="fw-bold" style="font-size: 12px; color: #33B27B;" id="dealsSave">${eachTopDealProduct[index].productSavePrice}</div>
      </div>
    </div>
  </div>
        `;
  }
};

// 页面加载完成后自动渲染数据
window.onload = function() {
  if (currentProductIndex !== null && allProducts.length > 0) {
    displayProducts();
  }
};

补充说明

  • Base64格式会使图片体积增加约30%,如果需要存储大量图片,建议通过后端存储图片并保存URL,而非存入localStorage
  • 存储完成后清空输入框,避免重复提交相同内容
  • 新增window.onload触发渲染逻辑,确保页面加载完成后再读取localStorage数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 03:27:39