要实现html表单的多文件上传,核心是使用带有multiple属性的type="file"输入框并设置表单enctype为multipart/form-data,通过javascript监听change事件读取filelist对象并动态生成文件列表显示,利用formdata收集文件并通过xmlhttprequest实现带进度条的异步上传,最终完成用户友好的多文件上传功能。

要实现HTML表单的多文件上传,核心在于HTML5的
input
multiple
实现多文件上传,首先你的表单需要一个正确的
enctype
multipart/form-data
input
type
file
multiple
name
name="files[]"
<form id="uploadForm" enctype="multipart/form-data" action="/upload-endpoint" method="post">
<label for="fileInput" style="display: block; margin-bottom: 10px;">选择文件:</label>
<input type="file" id="fileInput" name="files[]" multiple accept=".jpg,.png,.pdf,.doc,.docx">
<div id="fileListContainer" style="margin-top: 15px; border: 1px dashed #ccc; padding: 10px; min-height: 50px;">
<!-- 文件列表将在这里动态显示 -->
<p style="color: #666;">请选择文件...</p>
</div>
<button type="submit" style="margin-top: 20px; padding: 10px 20px; background-color: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">上传文件</button>
</form>接下来是前端显示文件列表的JavaScript部分。当用户选择文件后,
input
change
event.target.files
FileList
for...of
Array.from()
立即学习“前端免费学习笔记(深入)”;
document.addEventListener('DOMContentLoaded', () => {
const fileInput = document.getElementById('fileInput');
const fileListContainer = document.getElementById('fileListContainer');
fileInput.addEventListener('change', (event) => {
fileListContainer.innerHTML = ''; // 清空之前的列表,方便重新选择
const files = event.target.files;
if (files.length === 0) {
fileListContainer.innerHTML = '<p style="color: #666;">未选择任何文件。</p>';
return;
}
const ul = document.createElement('ul');
ul.style.listStyle = 'none';
ul.style.padding = '0';
ul.style.margin = '0';
Array.from(files).forEach(file => { // 将FileList转换为数组,方便一些数组方法的使用
const li = document.createElement('li');
li.style.marginBottom = '8px';
li.style.display = 'flex';
li.style.alignItems = 'center';
// 显示文件图标或预览
let iconHtml = '<span style="margin-right: 8px; font-size: 1.2em;">?</span>'; // 默认文件图标
if (file.type.startsWith('image/')) {
const img = document.createElement('img');
img.src = URL.createObjectURL(file); // 创建一个临时URL用于预览
img.style.width = '40px';
img.style.height = '40px';
img.style.marginRight = '8px';
img.style.borderRadius = '4px';
img.style.objectFit = 'cover';
img.onload = () => {
URL.revokeObjectURL(img.src); // 释放内存,当图片加载完成后
};
li.appendChild(img);
} else if (file.type.startsWith('video/')) {
iconHtml = '<span style="margin-right: 8px; font-size: 1.2em;">?</span>';
li.innerHTML += iconHtml; // 仅显示图标,不直接播放视频预览
} else if (file.type === 'application/pdf') {
iconHtml = '<span style="margin-right: 8px; font-size: 1.2em;">PDF</span>';
li.innerHTML += iconHtml;
} else {
li.innerHTML += iconHtml;
}
const fileNameSpan = document.createElement('span');
fileNameSpan.textContent = `${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`;
fileNameSpan.style.flexGrow = '1'; // 让文件名占据剩余空间
li.appendChild(fileNameSpan);
ul.appendChild(li);
});
fileListContainer.appendChild(ul);
});
});这里有个小细节,
URL.createObjectURL(file)
URL.revokeObjectURL()
这种情况太常见了。用户可能选了一堆文件,然后发现里面有几个是错的,或者干脆想全部重新选。前端的处理逻辑,最直接的就是在
input
change
fileListContainer.innerHTML = '';
change
event.target.files
如果用户只是想移除列表中的某个文件,那就需要更复杂的交互了。你可以在每个文件项旁边加一个“删除”按钮。当用户点击这个按钮时,你需要从当前的
FileList
FileList
selectedFiles = []
change
FileList
input
files
selectedFiles
input
files
FileList
大文件上传最怕的就是用户看着页面发呆,不知道是卡住了还是在上传。所以,显示上传进度条几乎是标配。这通常需要借助XMLHttpRequest(XHR)或Fetch API来异步上传文件,而不是直接提交整个表单。
使用XHR的话,
XMLHttpRequest.upload.onprogress
loaded
total
// 假设你有一个上传按钮和进度条元素
const uploadButton = document.getElementById('uploadForm').querySelector('button[type="submit"]');
const progressBar = document.createElement('div');
progressBar.style.width = '0%';
progressBar.style.height = '20px';
progressBar.style.backgroundColor = '#28a745';
progressBar.style.marginTop = '10px';
progressBar.style.borderRadius = '3px';
progressBar.style.transition = 'width 0.3s ease-in-out';
const progressText = document.createElement('span');
progressText.textContent = '0%';
progressText.style.marginLeft = '10px';
progressText.style.fontWeight = 'bold';
progressText.style.color = '#333';
uploadButton.parentNode.insertBefore(progressBar, uploadButton.nextSibling);
progressBar.parentNode.insertBefore(progressText, progressBar.nextSibling);
uploadButton.addEventListener('click', (e) => {
e.preventDefault(); // 阻止表单默认提交
const files = document.getElementById('fileInput').files;
if (files.length === 0) {
alert('请选择文件!');
return;
}
const formData = new FormData();
// 将所有选中的文件添加到FormData对象
Array.from(files).forEach(file => {
formData.append('files[]', file); // 这里的'files[]'要和后端接收的字段名一致
});
const xhr = new XMLHttpRequest();
xhr.open('POST', '/upload-endpoint', true); // '/upload-endpoint'是你的后端上传接口
xhr.upload.onprogress = (event) => {
if (event.lengthComputable) {
const percent = (event.loaded / event.total) * 100;
progressBar.style.width = percent + '%';
progressText.textContent = `${percent.toFixed(2)}%`;
// progressBar.setAttribute('aria-valuenow', percent.toFixed(2)); // 如果是带有aria属性的进度条
}
};
xhr.onload = () => {
if (xhr.status === 200) {
console.log('上传成功!', xhr.responseText);
alert('文件上传成功!');
progressBar.style.width = '0%'; // 重置进度条
progressText.textContent = '0%';
// 清空文件列表或做其他处理
document.getElementById('fileInput').value = ''; // 清空input的选择
document.getElementById('fileListContainer').innerHTML = '<p style="color: #666;">请选择文件...</p>';
} else {
console.error('上传失败!', xhr.status, xhr.responseText);
alert(`文件上传失败!状态码: ${xhr.status}`);
progressBar.style.width = '0%'; // 重置进度条
progressText.textContent = '0%';
}
};以上就是HTML表单如何实现多文件上传?怎样显示上传的文件列表?的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号