img标签的src属性使用base64上传图片后刷新网页src显示问题

背景:使用input的file指定上传图片,然后把他作为 img 的 src 属性,显示没有问题,但是如果刷新网页的话就img的src属性就会显示未知
百度后得知可能是浏览器不会缓存的缘故,那换成背景图可以吗?他这里的这个未知是什么意思呢?


```html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <input type="file" id="up" accept="image/*">
    <!-- <input type="file" name="pic" id="up" accept="image/*"> -->
    <img src="" width="200px" id="img" height="200px" alt="">
</body>
<script src="./source//jQuery/jquery.3.5.1.min.js"></script>
<script>
    let up = document.querySelector('#up')
    let img = document.querySelector('#img')
    up.onchange = function () {
        let fileDate = this.files[0]
        let pettern = /^image/
        if (!pettern.test(fileDate.type)) {
            alert('图片格式不正确')
            return
        }
        let reader = new FileReader()
        reader.readAsDataURL(fileDate)//及将图片转化为 base64位
        reader.onload = function (e) {
            console.log(e)
            console.log(this.result)//需要的数据
            // jq设置 src属性
            $('#img').attr('src', this.result)
        }
    }
</script>

</html>

使用localStorage本地存储可以实现

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>

  <body>
    <input type="file" id="up" accept="image/*" />
    <!-- <input type="file" name="pic" id="up" accept="image/*"> -->
    <img src="" width="200px" id="img" height="200px" alt="" />
  </body>
  <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <script>
    window.onload = function () {
      // 刷新进入,查询localStorage中存在key为imgSrcBase64Temp
      const imgSrcBase64Temp = window.localStorage.getItem("imgSrcBase64Temp");
      // 将imgSrcBase64Temp赋值给img的src,实现保存上次上传的图片
      if (imgSrcBase64Temp) $("#img").attr("src", imgSrcBase64Temp);
    };
    let up = document.querySelector("#up");
    let img = document.querySelector("#img");
    up.onchange = function () {
      let fileDate = this.files[0];
      let pettern = /^image/;
      if (!pettern.test(fileDate.type)) {
        alert("图片格式不正确");
        return;
      }
      let reader = new FileReader();
      reader.readAsDataURL(fileDate); //及将图片转化为 base64位
      reader.onload = function (e) {
        console.log(e);
        console.log(this.result); //需要的数据
        window.localStorage.setItem("imgSrcBase64Temp", this.result); // 存在localStorage中key为imgSrcBase64Temp
        // jq设置 src属性
        $("#img").attr("src", this.result);
      };
    };
  </script>
</html>

你网页刷新有没有处罚onchange事件,img的src属性本来就是空的,怎么会显示图片呢

應該在wind.onload事件裏面寫圖片賦值的方法