HTML5新增API FileReader 显示缩略图

javascript 复制代码
<!DOCTYPE html>
<html lang="CH-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>生成图片</title>
  </head>
  <body>
    <div class="content">
      <input type="file" name="file" id="file" />
      <img src="" class="img" alt="图片" />
    </div>
  </body>
</html>

<script>
  const file = document.querySelector("#file");
  const img = document.querySelector("img");
  // 添加监听内容变化时读取文件
  file.addEventListener("change", () => {
    // 实例化了一个reader对象
    let reader = new FileReader();
    // 当这个文件的内容读取完毕之后, 会把内容存放到 result里面,并调用load方法
    reader.addEventListener("load", () => {
      img.src = reader.result;
    });
    // 读取文件
    reader.readAsDataURL(file.files[0]);
  });
</script>
<style>
  * {
    font-size: 12px;
    margin: 0;
    padding: 0;
  }
  .content {
    margin: 20px;
    height: 500px;
    border: solid #dddd 1px;
    display: flex;
    flex-direction: column;
    align-items: center;
  }
  .content input {
    margin-top: 10px;
  }
  .img {
    margin-top: 10px;
    height: 300px;
  }
</style>

效果

相关推荐
WeiXin_DZbishe4 天前
基于django在线音乐数据采集的设计与实现-计算机毕设 附源码 22647
javascript·spring boot·mysql·django·node.js·php·html5
长城20244 天前
HTML5中表单的pattern属性解析
前端·正则表达式·html·html5·pattern·pattern属性·pattern正则表达式
PieroPc5 天前
HTML5 Canvas 平台跳跃游戏
前端·游戏·html5
长城20245 天前
HTML5 中<meter>标签的属性说明
html·html5·meter·meter标签·meter属性·meter标签属性
CappuccinoRose6 天前
HTML语法学习文档 - 汇总篇
前端·学习·html5
henry1010106 天前
DeepSeek生成的HTML5小游戏 -- 投篮小能手
前端·javascript·css·游戏·html5
享誉霸王7 天前
15、告别混乱!Vue3复杂项目的规范搭建与基础库封装实战
前端·javascript·vue.js·前端框架·json·firefox·html5
CappuccinoRose7 天前
HTML语法学习文档(九)
前端·学习·架构·html5
linux_cfan8 天前
拒绝“黑屏”与“哑剧”:Web视频播放器UX体验与自动播放选型指南 (2026版)
前端·javascript·音视频·html5·ux
CappuccinoRose9 天前
HTML语法学习文档(五)
前端·html·html5·表单