js实现上传图片
使用HTML5的File API实现图片上传
创建一个文件输入元素,监听change事件获取用户选择的图片文件
<input type="file" id="imageUpload" accept="image/*">
通过FileReader读取图片文件内容
document.getElementById('imageUpload').addEventListener('change', function(e) {
const file = e.target.files[0];
if (!file.type.match('image.*')) {
alert('请选择图片文件');
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const imgPreview = document.createElement('img');
imgPreview.src = e.target.result;
document.body.appendChild(imgPreview);
};
reader.readAsDataURL(file);
});
使用FormData进行AJAX上传
创建FormData对象并附加图片文件
const formData = new FormData();
formData.append('image', file);
// 使用fetch API发送
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log('上传成功', data))
.catch(error => console.error('上传失败', error));
使用XMLHttpRequest实现上传进度监控
通过xhr.upload对象获取上传进度
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percent = Math.round((e.loaded / e.total) * 100);
console.log(`上传进度: ${percent}%`);
}
};
xhr.onload = function() {
if (xhr.status === 200) {
console.log('上传完成');
}
};
xhr.send(formData);
图片压缩处理
使用canvas对图片进行压缩
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('multiUpload').addEventListener('change', function(e) {
const files = Array.from(e.target.files);
const uploadPromises = files.map(file => {
return compressImage(file, 800, 800, 0.7)
.then(blob => {
const formData = new FormData();
formData.append('images[]', blob, file.name);
return fetch('/upload', {
method: 'POST',
body: formData
});
});
});
Promise.all(uploadPromises)
.then(responses => console.log('所有文件上传完成'))
.catch(error => console.error('上传出错', error));
});






