JS实现头像上传预览
实现头像上传预览的方法
HTML部分 创建一个文件输入框和一个用于预览的图片元素:
<input type="file" id="avatar-upload" accept="image/*">
<img id="avatar-preview" src="#" alt="头像预览" style="display:none; max-width:200px;">
JavaScript部分 监听文件输入变化并处理预览:
document.getElementById('avatar-upload').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const preview = document.getElementById('avatar-preview');
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.style.display = 'block';
}
reader.readAsDataURL(file);
});
添加图片验证功能
在读取文件前检查文件类型和大小:
const MAX_SIZE = 2 * 1024 * 1024; // 2MB
if (!file.type.match('image.*')) {
alert('请选择图片文件');
return;
}
if (file.size > MAX_SIZE) {
alert('图片大小不能超过2MB');
return;
}
使用canvas压缩图片
对大图片进行压缩处理:
function compressImage(file, callback) {
const img = new Image();
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
img.onload = function() {
const MAX_WIDTH = 800;
const MAX_HEIGHT = 800;
let width = img.width;
let height = img.height;
if (width > height) {
if (width > MAX_WIDTH) {
height *= MAX_WIDTH / width;
width = MAX_WIDTH;
}
} else {
if (height > MAX_HEIGHT) {
width *= MAX_HEIGHT / height;
height = MAX_HEIGHT;
}
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
callback(canvas.toDataURL('image/jpeg', 0.7));
};
img.src = URL.createObjectURL(file);
}
完整实现示例
document.getElementById('avatar-upload').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const MAX_SIZE = 2 * 1024 * 1024;
if (!file.type.match('image.*')) {
alert('请选择图片文件');
return;
}
if (file.size > MAX_SIZE) {
compressImage(file, function(compressedDataUrl) {
const preview = document.getElementById('avatar-preview');
preview.src = compressedDataUrl;
preview.style.display = 'block';
});
} else {
const preview = document.getElementById('avatar-preview');
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.style.display = 'block';
}
reader.readAsDataURL(file);
}
});
样式优化建议
为上传区域添加更好的视觉效果:
#avatar-preview {
border-radius: 50%;
object-fit: cover;
width: 120px;
height: 120px;
margin-top: 10px;
border: 2px solid #eee;
}
#avatar-upload {
display: none;
}
.upload-label {
display: inline-block;
padding: 8px 15px;
background: #4CAF50;
color: white;
cursor: pointer;
border-radius: 4px;
}
对应的HTML调整:
<label for="avatar-upload" class="upload-label">选择头像</label>
<input type="file" id="avatar-upload" accept="image/*">






