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>

效果

相关推荐
尘寰ya15 小时前
前端面试-HTML5与CSS3
前端·面试·css3·html5
一只小风华~19 小时前
Web前端 (CSS篇)
前端·css·html·html5
一只小风华~1 天前
web前端开发:CSS的常用选择器
前端·css·html·html5
xcLeigh1 天前
HTML5好看的水果蔬菜在线商城网站源码系列模板4
java·前端·源码·html5
qq_424409191 天前
uniapp的h5,打开的时候,标题会一闪而过应用名称,再显示当前页面的标题
微信小程序·uni-app·html5
HaushoLin2 天前
ERR_PNPM_DLX_NO_BIN No binaries found in tailwindcss
前端·vue.js·css3·html5
LAY家的奶栗子是德云女孩3 天前
HTML5+CSS前端开发【保姆级教学】+超链接标签
前端·css·笔记·html5
烂蜻蜓3 天前
HTML5 Web 存储:超越 Cookie 的本地存储新选择
前端·html·html5
烂蜻蜓4 天前
在 HTML5 中使用 MathML 展示数学公式
前端·html·html5
烂蜻蜓5 天前
深入理解 HTML5 语义元素:提升网页结构与可访问性
前端·html·html5