js实现图片上传预览
使用FileReader实现图片上传预览
通过HTML5的FileReader API可以读取用户上传的图片文件并显示预览。需要创建文件输入元素和图片预览容器。
<input type="file" id="upload" accept="image/*">
<img id="preview" style="max-width: 300px; display: none;">
document.getElementById('upload').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file.type.match('image.*')) return;
const reader = new FileReader();
reader.onload = function(e) {
const preview = document.getElementById('preview');
preview.src = e.target.result;
preview.style.display = 'block';
};
reader.readAsDataURL(file);
});
使用URL.createObjectURL实现预览
这种方法不需要等待文件完全读取,性能更好但需要手动释放内存。
document.getElementById('upload').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file) return;
const preview = document.getElementById('preview');
if (preview.src) URL.revokeObjectURL(preview.src);
preview.src = URL.createObjectURL(file);
preview.style.display = 'block';
});
多图片预览实现
对于需要同时预览多个图片的场景,可以使用以下方法:
<input type="file" id="multiUpload" accept="image/*" multiple>
<div id="previewContainer"></div>
document.getElementById('multiUpload').addEventListener('change', function(e) {
const container = document.getElementById('previewContainer');
container.innerHTML = '';
Array.from(e.target.files).forEach(file => {
if (!file.type.match('image.*')) return;
const img = document.createElement('img');
img.style.maxWidth = '200px';
img.style.margin = '5px';
img.src = URL.createObjectURL(file);
container.appendChild(img);
});
});
图片压缩和调整大小
上传前可以对图片进行压缩处理:
function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve) => {
const img = new Image();
img.src = URL.createObjectURL(file);
img.onload = () => {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height *= maxWidth / width;
width = maxWidth;
}
if (height > maxHeight) {
width *= maxHeight / height;
height = maxHeight;
}
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob(resolve, 'image/jpeg', quality);
};
});
}
// 使用示例
document.getElementById('upload').addEventListener('change', async (e) => {
const file = e.target.files[0];
const compressedFile = await compressImage(file, 800, 800, 0.7);
// 使用compressedFile进行上传或预览
});
拖放上传预览实现
支持拖放操作的图片预览:
<div id="dropArea" style="border: 2px dashed #ccc; padding: 20px;">
拖放图片到这里
</div>
<div id="dropPreview"></div>
const dropArea = document.getElementById('dropArea');
['dragenter', 'dragover', 'dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, preventDefaults, false);
});
function preventDefaults(e) {
e.preventDefault();
e.stopPropagation();
}
['dragenter', 'dragover'].forEach(eventName => {
dropArea.addEventListener(eventName, highlight, false);
});
['dragleave', 'drop'].forEach(eventName => {
dropArea.addEventListener(eventName, unhighlight, false);
});
function highlight() {
dropArea.style.borderColor = '#666';
}
function unhighlight() {
dropArea.style.borderColor = '#ccc';
}
dropArea.addEventListener('drop', handleDrop, false);
function handleDrop(e) {
const dt = e.dataTransfer;
const files = dt.files;
const preview = document.getElementById('dropPreview');
preview.innerHTML = '';
Array.from(files).forEach(file => {
if (!file.type.match('image.*')) return;
const img = document.createElement('img');
img.style.maxWidth = '200px';
img.style.margin = '5px';
img.src = URL.createObjectURL(file);
preview.appendChild(img);
});
}






