<!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>