js图片上传实现
图片上传的基本实现
使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。以下是一个基础实现示例:
<input type="file" id="imageUpload" accept="image/*">
<button onclick="uploadImage()">上传图片</button>
<img id="preview" style="max-width: 300px; display: none;">
function uploadImage() {
const fileInput = document.getElementById('imageUpload');
const file = fileInput.files[0];
if (!file) {
alert('请选择图片文件');
return;
}
// 预览图片
const preview = document.getElementById('preview');
const reader = new FileReader();
reader.onload = function(e) {
preview.src = e.target.result;
preview.style.display = 'block';
};
reader.readAsDataURL(file);
}
使用FormData上传到服务器
通过XMLHttpRequest或Fetch API将图片发送到服务器:
function uploadToServer() {
const fileInput = document.getElementById('imageUpload');
const file = fileInput.files[0];
if (!file) return;
const formData = new FormData();
formData.append('image', file);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
console.log('上传成功:', data);
})
.catch(error => {
console.error('上传失败:', error);
});
}
图片压缩处理
在上传前可以使用Canvas API对图片进行压缩:
function compressImage(file, maxWidth = 800, quality = 0.7) {
return new Promise((resolve) => {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = function(event) {
const img = new Image();
img.src = event.target.result;
img.onload = function() {
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
let width = img.width;
let height = img.height;
if (width > maxWidth) {
height = (maxWidth / width) * height;
width = maxWidth;
}
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
canvas.toBlob((blob) => {
resolve(new File([blob], file.name, {
type: 'image/jpeg',
lastModified: Date.now()
}));
}, 'image/jpeg', quality);
};
};
});
}
多图片上传实现
通过multiple属性允许选择多个文件:
<input type="file" id="multiUpload" accept="image/*" multiple>
<button onclick="uploadMultiple()">上传多图</button>
async function uploadMultiple() {
const fileInput = document.getElementById('multiUpload');
const files = Array.from(fileInput.files);
if (files.length === 0) return;
const compressedFiles = await Promise.all(
files.map(file => compressImage(file))
);
const formData = new FormData();
compressedFiles.forEach((file, index) => {
formData.append(`images[${index}]`, file);
});
// 上传逻辑同上
}
使用第三方库简化操作
可以考虑使用现成的库如Dropzone.js或FilePond:
<!-- Dropzone.js示例 -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/dropzone/5.9.3/dropzone.min.js"></script>
<form action="/upload" class="dropzone" id="myDropzone"></form>
<script>
Dropzone.options.myDropzone = {
paramName: "file",
maxFilesize: 5, // MB
acceptedFiles: "image/*",
dictDefaultMessage: "拖放图片到这里或点击上传",
dictFileTooBig: "文件过大 ({{filesize}}MB). 最大支持: {{maxFilesize}}MB."
};
</script>
进度显示实现
上传过程中显示进度条:
<div class="progress">
<div id="progressBar" class="progress-bar" style="width: 0%"></div>
</div>
function uploadWithProgress(file) {
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('image', file);
xhr.upload.addEventListener('progress', (e) => {
if (e.lengthComputable) {
const percent = (e.loaded / e.total) * 100;
document.getElementById('progressBar').style.width = `${percent}%`;
}
});
xhr.open('POST', '/upload');
xhr.send(formData);
}






