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>

效果

相关推荐
ZC跨境爬虫1 天前
跟着 MDN 学CSS day_3:(为一个传记页面添加样式)
前端·javascript·css·ui·音视频·html5
燐妤1 天前
前端HTML编程6:ES6与前后端交互
前端·javascript·学习·html5
摇滚侠3 天前
14 响应式网页 WEB 前端 WEB 开发 HTML5 + CSS3 + 移动 WEB
前端·css3·html5
2601_958492554 天前
Optimizing Engagement with Freehead Skate - HTML5 Game - Construct 3
前端·html·html5
2601_958492554 天前
Performance Audit of Paper Boats Racing - HTML5 Racing Game
前端·html·html5
摇滚侠4 天前
13 移动端 WEB 前端 WEB 开发 HTML5 + CSS3 + 移动 WEB
前端·css3·html5
2601_958492555 天前
A Technical Log: Hosting Gravity Dunk - HTML5 Casual game
前端·html·html5
2601_958492555 天前
Behavioral Analysis of HTML5 Trivia Integration
前端·html·html5
2601_958492555 天前
Webmaster Notes: Deploying HTML5 Word Environments
前端·word·html5
向日的葵0066 天前
CSDN博客文章-爪印之约宠物收养管理系统
mysql·css3·html5·fastapi·宠物