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>

效果

相关推荐
Yvonne爱编码4 小时前
CSS- 4.2 相对定位(position: relative)
前端·css·状态模式·html5·hbuilder
高建伟-joe8 小时前
内容安全:使用开源框架Caffe实现上传图片进行敏感内容识别
人工智能·python·深度学习·flask·开源·html5·caffe
源码方舟9 小时前
【HTML5】【AJAX的几种封装方法详解】
ajax·okhttp·html5
Alice-YUE1 天前
【HTML5学习笔记1】html标签(上)
前端·笔记·学习·html·html5
Alice-YUE1 天前
【HTML5学习笔记2】html标签(下)
前端·笔记·html·html5
Yvonne爱编码2 天前
CSS- 2.1 实战之图文混排、表格、表单
前端·css·html·github·状态模式·html5·hbuilder
Yvonne爱编码2 天前
CSS- 1.1 css选择器
前端·css·状态模式·html5·hbuilder
Yvonne爱编码2 天前
HTML-3.3 表格布局(学校官网简易布局实例)
前端·html·github·html5·hbuilder
淡笑沐白2 天前
探索Turn.js:打造惊艳的3D翻页效果
javascript·html5·turn.js
酷爱码3 天前
HTML5表格语法格式详解
前端·html·html5