图片上传实现js
使用FileReader API读取图片文件
通过HTML的<input type="file">元素获取用户选择的图片文件,使用FileReader对象将文件转换为DataURL或ArrayBuffer。
<input type="file" id="imageUpload" accept="image/*">
<script>
document.getElementById('imageUpload').addEventListener('change', function(event) {
const file = event.target.files[0];
if (file) {
const reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result); // 输出Base64编码的图片数据
};
reader.readAsDataURL(file);
}
});
</script>
使用Canvas压缩图片
通过Canvas API调整图片尺寸和质量,减少上传文件大小。

function compressImage(file, maxWidth, maxHeight, quality) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.onload = function(event) {
const img = new Image();
img.onload = function() {
const canvas = document.createElement('canvas');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height = Math.round((height * maxWidth) / width);
width = maxWidth;
}
if (height > maxHeight) {
width = Math.round((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);
};
img.src = event.target.result;
};
reader.readAsDataURL(file);
});
}
使用FormData上传图片
创建FormData对象并通过XMLHttpRequest或fetch API发送图片数据到服务器。

async function uploadImage(file) {
const formData = new FormData();
formData.append('image', file);
try {
const response = await fetch('/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
console.log('上传成功:', result);
} catch (error) {
console.error('上传失败:', error);
}
}
使用第三方库简化流程
利用现成的JavaScript库如Dropzone.js或Uppy简化图片上传实现。
<!-- 使用Dropzone.js示例 -->
<link rel="stylesheet" href="https://unpkg.com/dropzone@5/dist/min/dropzone.min.css">
<script src="https://unpkg.com/dropzone@5/dist/min/dropzone.min.js"></script>
<div id="myDropzone" class="dropzone"></div>
<script>
Dropzone.options.myDropzone = {
url: "/upload",
paramName: "file",
maxFilesize: 2, // MB
acceptedFiles: "image/*",
addRemoveLinks: true
};
</script>
进度显示和错误处理
实现上传进度监控和错误处理机制,提升用户体验。
function uploadWithProgress(file) {
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload', true);
xhr.upload.onprogress = function(e) {
if (e.lengthComputable) {
const percentComplete = (e.loaded / e.total) * 100;
console.log(`上传进度: ${percentComplete.toFixed(2)}%`);
}
};
xhr.onload = function() {
if (xhr.status === 200) {
console.log('上传完成');
} else {
console.error('上传失败');
}
};
xhr.onerror = function() {
console.error('网络错误');
};
const formData = new FormData();
formData.append('image', file);
xhr.send(formData);
}






