<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>原生实现图片预览功能</title>
</head>
<body>
<label for="file">点击上传文件</label>
<input id="file" onchange="uploadFiles()" accept="image/png,image/jpeg" type='file' multiple />
<div class="preview">
<p>No files currently selected for upload</p>
</div>
<script>
const input = document.querySelector('input');
input.style.opacity = 0;
function uploadFiles() {
const files = input.files; // 从元素的files属性获取文件列表
const preview = document.querySelector('.preview');
while(preview.firstChild) { // 每次都清空原有列表
preview.removeChild(preview.firstChild);
}
const ol = document.createElement('ol');
preview.appendChild(ol);
for(let file of files) {
const li = document.createElement('li');
const newLi = showFiles(file, li, preview);
preview.appendChild(newLi);
}
}
function showFiles(file, li) {
const { name, size, type } = file;
const isValidate = validateFileType(type)
if (isValidate) {
const img = document.createElement('img');
img.src = window.URL.createObjectURL(file); //***生成文件路径,添加到img的src
const sizeChanged = getSize(size);
const textContent = document.createTextNode(name + ': ' + sizeChanged);
li.appendChild(textContent);
li.appendChild(img);
} else {
const textContent = document.createTextNode("InValide File Type");
li.appendChild(textContent);
}
return li;
}
function getSize(size) { // 按照用户习惯计算大小
if (size<1024) {
return size + 'byte';
} else if (size<1048576) {
return (size/1024).toFixed(1) + 'KB';
} else {
return (size/1048576).toFixed(1) + 'MB';
}
}
const fileTypes = ['image/png', 'image/jpeg'];
function validateFileType(type) { // 验证文件类型
if (!fileTypes.includes(type)) {
return false;
}
return true;
}
</script>
</body>
</html>

最新文章

  1. SQL Server 日期和时间函数
  2. win10 下 gulp-sass 无法使用的解决
  3. UIAlertController的使用
  4. Linux环境下安装Tigase XMPP Server
  5. java之浮点数(笔记)
  6. 【Android】Android清除本地数据缓存代码
  7. android studio自动导包
  8. A fatal error has been detected by the Java Runtime Environment(jdk 1.6的一个BUG)
  9. Oracle NoLogging Append 方式减少批量insert的redo_size
  10. 01TCP/IP基础
  11. careercup-链表 2.4
  12. linux sudo环境变量设置
  13. SAE Python使用经验 好文推荐
  14. SQLserver2012 tcp/ip 1433port问题解决方法
  15. 如何构造一个简单的USB过滤驱动程序
  16. Android Studio 不得不知的20大快捷键
  17. headfirst设计模式(5)—工厂模式体系分析及抽象工厂模式
  18. SSM框架使用
  19. __x__(6)0905第二天__标签属性=“值”
  20. 783. Minimum Distance Between BST Node

热门文章

  1. css — 定位、背景图、水平垂直居中
  2. 探索grafana
  3. STM32启动文件详解
  4. JVM Java 内存区域透彻分析(转)
  5. raise ImproperlyConfigured(&#39;mysqlclient 1.3.13 or newer is required; you have %s.&#39; % Database.__version__)
  6. .NET Core使用swagger遇到的坑
  7. 【web】使用ionic搭建移动端项目 icon-radio 标签在ios下全部选中的问题
  8. buffer 与 cache 的区别
  9. ubuntu16.04 一键安装nginx-rtmp
  10. springboot2.0(二)