JS实现上传
上传文件的基本实现
使用HTML的<input type="file">元素配合JavaScript的File API可以实现文件上传功能。以下是一个基础示例:
<input type="file" id="fileInput">
<button onclick="uploadFile()">上传文件</button>
function uploadFile() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('请选择文件');
return;
}
const formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log('上传成功:', data))
.catch(error => console.error('上传失败:', error));
}
多文件上传
通过添加multiple属性可以实现多文件选择:

<input type="file" id="fileInput" multiple>
function uploadFiles() {
const fileInput = document.getElementById('fileInput');
const files = fileInput.files;
if (files.length === 0) {
alert('请选择文件');
return;
}
const formData = new FormData();
for (let i = 0; i < files.length; i++) {
formData.append('files', files[i]);
}
fetch('/upload-multiple', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log('上传成功:', data))
.catch(error => console.error('上传失败:', error));
}
上传进度显示
使用XMLHttpRequest可以获取上传进度:

function uploadWithProgress() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('请选择文件');
return;
}
const xhr = new XMLHttpRequest();
const formData = new FormData();
formData.append('file', file);
xhr.upload.addEventListener('progress', (event) => {
if (event.lengthComputable) {
const percent = Math.round((event.loaded / event.total) * 100);
console.log(`上传进度: ${percent}%`);
}
});
xhr.addEventListener('load', () => {
console.log('上传完成');
});
xhr.addEventListener('error', () => {
console.error('上传出错');
});
xhr.open('POST', '/upload', true);
xhr.send(formData);
}
文件预览与验证
在上传前可以对文件进行预览和验证:
function previewAndUpload() {
const fileInput = document.getElementById('fileInput');
const file = fileInput.files[0];
if (!file) {
alert('请选择文件');
return;
}
// 验证文件类型
const allowedTypes = ['image/jpeg', 'image/png'];
if (!allowedTypes.includes(file.type)) {
alert('只允许上传JPEG或PNG图片');
return;
}
// 验证文件大小 (5MB以内)
if (file.size > 5 * 1024 * 1024) {
alert('文件大小不能超过5MB');
return;
}
// 图片预览
const reader = new FileReader();
reader.onload = (e) => {
const preview = document.createElement('img');
preview.src = e.target.result;
preview.style.maxWidth = '300px';
document.body.appendChild(preview);
};
reader.readAsDataURL(file);
// 上传文件
const formData = new FormData();
formData.append('file', file);
fetch('/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log('上传成功:', data))
.catch(error => console.error('上传失败:', error));
}
使用第三方库实现上传
对于更复杂的需求,可以使用如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>
Dropzone.options.myDropzone = {
url: "/upload",
paramName: "file",
maxFilesize: 5, // MB
acceptedFiles: "image/*",
addRemoveLinks: true,
init: function() {
this.on("success", function(file, response) {
console.log("文件上传成功", response);
});
this.on("error", function(file, errorMessage) {
console.error("上传出错", errorMessage);
});
}
};






