流程:
1.获取上传文件
2.创建一个文件读取对象
3.把文件给文件读取对象 生成url
4.把url赋值给图片等
<!DOCTYPE html>
<html>
<head>
<title>文件上传</title>
<style>
/* 样式化上传区域 */
#upload-area {
border: 2px dashed #ccc;
padding: 20px;
text-align: center;
}
#preview-image {
max-width: 300px;
}
</style>
</head>
<body>
<div id="upload-area">
<input type="file" id="file-input" />
<br />
<img id="preview-image" />
</div>
<script>
// 文件选择后预览功能
const fileInput = document.getElementById('file-input');
const previewImage = document.getElementById('preview-image');
fileInput.addEventListener('change', function() {
const file = fileInput.files[0];
const reader = new FileReader();
reader.onload = function(e) {
previewImage.src = e.target.result;
}
reader.readAsDataURL(file);
});
</script>
</body>
</html>