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>

效果

相关推荐
ヤ鬧鬧o.14 小时前
IDE风格的布局界面
javascript·html5
qq_4061761414 小时前
什么是模块化
开发语言·前端·javascript·ajax·html5
HIT_Weston1 天前
85、【Ubuntu】【Hugo】搭建私人博客:文章目录(四)
linux·ubuntu·html5
谷哥的小弟2 天前
HTML5新手练习项目—新年祝福(附源码)
前端·源码·html5·项目
MoonPointer-Byte2 天前
[特殊字符]The Omniscient Tome | 全知之书
javascript·html5
行思理2 天前
css 样式新手教程
前端·css·html5
空白3 天前
自学HTML5+CSS3丨第三天丨详解SEO
前端·css3·html5
xun_li_3 天前
2024---2025年前端开发的就业现状及前景
css·html·css3·html5
打工人小夏3 天前
前端面试题
前端·css·前端框架·vue·html·es6·html5
旧梦吟4 天前
脚本网页 双子星棋
算法·flask·游戏引擎·css3·html5