jq上传多张图片(带进度条)

这是一个HTML示例,展示了如何使用XMLHttpRequest2实现多张图片上传,并在上传过程中显示进度条。通过创建FormData对象,将选择的文件逐个追加到表单数据中,然后通过POST请求发送到服务器。xhr.upload.onprogress事件用于监听上传进度,并更新进度条显示。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>xhr2</title>
</head>
<body>
<div style="text-align: center; margin: 100px">
<input type="file" id="file" name="file" multiple="multiple">
<progress id="uploadprogress" min="0" max="100" value="0">0</progress>
<button onclick="xhr2()">OK</button>
</div>
<script>
function xhr2() {
var xhr = new XMLHttpRequest();//第一步
//定义表单变量
var file = document.getElementById('file').files;
//console.log(file.length);
//新建一个FormData对象
var formData = new FormData(); //++++++++++
formData.append("enctype","multipart/form-data");
//追加文件数据
for (i = 0; i < file.length; i++) {
formData.append("file[" + i + "]", file[i]); //++++++++++
}
//formData.append("file", file[0]); //++++++++++


//post方式
xhr.open('POST', '/common/doUpload'); //第二步骤
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var complete = (event.loaded / event.total * 100 | 0);
var progress = document.getElementById('uploadprogress');
progress.value = progress.innerHTML = complete;
}
};
//发送请求
xhr.send(formData); //第三步骤
//ajax返回
xhr.onreadystatechange = function() { //第四步
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText);
}
};
//设置超时时间
xhr.timeout = 100000;
xhr.ontimeout = function(event) {
alert('请求超时!');
}
}
</script>
</body>
</html>
<think>我们使用jQuery和XMLHttpRequest的upload事件来实现文件上传进度条。 由于用户要求使用jQuery,我们将采用jQuery的ajax方法,并利用xhr选项来监听上传进度。 同时,我们将实现多文件上传,并为每个文件显示独立的进度条。 步骤: 1. HTML结构:文件选择输入框,上传按钮,文件列表容器(用于显示每个文件的上传进度条) 2. 使用FormData来构建上传数据 3. 在ajax请求中,通过xhr选项创建XMLHttpRequest对象,并监听progress事件 4. 为每个文件创建独立的进度条DOM元素 5. 实现取消上传功能(可选) 注意:由于多文件上传需要为每个文件单独创建请求,因此我们将遍历每个文件并单独发送请求。 参考用户提供的引用[1]中的代码,它展示了如何通过xhr选项监听上传进度,并更新进度条。 我们将实现一个多文件上传的示例,每个文件都有独立的进度条。 同时,我们也会考虑文件类型和大小的验证。 由于用户要求使用jQuery,我们将使用jQuery来处理事件和DOM操作。 以下为完整代码:</think># jQuery多文件上传与独立进度条实现 下面我将实现一个完整的多文件上传解决方案,包含独立的进度条显示、文件预览、取消上传等功能。 ## 解决方案思路 1. 使用FormData处理多文件上传 2. 通过XMLHttpRequest的progress事件获取上传进度 3. 为每个文件创建独立的进度条和UI元素 4. 实现文件预览和取消上传功能 ## 完整实现代码 ```html <!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>jQuery多文件上传进度条</title> <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <style> * { box-sizing: border-box; margin: 0; padding: 0; font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; } body { background: linear-gradient(135deg, #f5f7fa, #e4edf5); min-height: 100vh; display: flex; justify-content: center; align-items: center; padding: 20px; } .container { background-color: white; border-radius: 12px; box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1); width: 100%; max-width: 800px; padding: 30px; } h1 { text-align: center; color: #2c3e50; margin-bottom: 20px; font-weight: 600; } .upload-area { border: 2px dashed #3498db; border-radius: 8px; padding: 30px; text-align: center; background-color: #f8fafc; margin-bottom: 25px; transition: all 0.3s ease; cursor: pointer; } .upload-area:hover, .upload-area.dragover { background-color: #e8f4fe; border-color: #2980b9; } .upload-icon { font-size: 48px; color: #3498db; margin-bottom: 15px; } .file-input { display: none; } .btn { background-color: #3498db; color: white; border: none; padding: 12px 25px; border-radius: 6px; font-size: 16px; font-weight: 500; cursor: pointer; transition: background-color 0.3s; display: inline-block; margin-top: 15px; } .btn:hover { background-color: #2980b9; } .btn:disabled { background-color: #bdc3c7; cursor: not-allowed; } .file-list { margin-top: 25px; max-height: 400px; overflow-y: auto; } .file-item { display: flex; align-items: center; padding: 15px; border: 1px solid #e2e8f0; border-radius: 8px; margin-bottom: 15px; background-color: white; box-shadow: 0 2px 5px rgba(0, 0, 0, 0.05); transition: transform 0.2s; } .file-item:hover { transform: translateY(-2px); box-shadow: 0 4px 8px rgba(0, 0, 0, 0.08); } .file-preview { width: 60px; height: 60px; border-radius: 6px; object-fit: cover; margin-right: 15px; background-color: #f1f5f9; display: flex; align-items: center; justify-content: center; font-size: 24px; color: #64748b; } .file-info { flex-grow: 1; min-width: 0; } .file-name { font-weight: 500; color: #2d3748; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-bottom: 5px; } .file-size { color: #718096; font-size: 13px; } .progress-container { width: 100%; margin-top: 10px; } .progress-bar { height: 8px; background-color: #e2e8f0; border-radius: 4px; overflow: hidden; } .progress-fill { height: 100%; background: linear-gradient(90deg, #3498db, #2ecc71); width: 0%; transition: width 0.3s ease; } .progress-info { display: flex; justify-content: space-between; margin-top: 5px; font-size: 13px; color: #64748b; } .file-actions { display: flex; margin-left: 15px; } .action-btn { background: none; border: none; color: #718096; cursor: pointer; font-size: 18px; margin-left: 10px; transition: color 0.2s; } .cancel-btn:hover { color: #e74c3c; } .success-message { text-align: center; color: #27ae60; font-weight: 500; margin-top: 20px; padding: 10px; background-color: rgba(39, 174, 96, 0.1); border-radius: 6px; display: none; } .error-message { color: #e74c3c; font-size: 14px; margin-top: 10px; text-align: center; display: none; } .stats { display: flex; justify-content: space-between; margin-top: 20px; padding-top: 15px; border-top: 1px solid #e2e8f0; color: #64748b; font-size: 14px; } </style> </head> <body> <div class="container"> <h1>jQuery多文件上传</h1> <p style="text-align: center; color: #64748b; margin-bottom: 20px;">支持拖放文件上传显示独立进度条</p> <div class="upload-area" id="dropArea"> <div class="upload-icon">📁</div> <h3>拖放文件到此处或点击选择文件</h3> <p class="file-types">支持图片、文档、PDF等格式</p> <input type="file" id="fileInput" class="file-input" multiple> <button class="btn" id="selectBtn">选择文件</button> </div> <div class="error-message" id="errorMessage"></div> <div class="file-list" id="fileList"></div> <div style="text-align: center; margin-top: 20px;"> <button class="btn" id="uploadBtn" disabled>开始上传</button> </div> <div class="success-message" id="successMessage"></div> <div class="stats"> <div>已选择: <span id="fileCount">0</span> 个文件</div> <div>总大小: <span id="totalSize">0 B</span></div> </div> </div> <script> $(document).ready(function() { // 存储文件信息 let files = []; // 存储上传请求 const uploadRequests = {}; // 选择文件按钮点击事件 $('#selectBtn').click(function() { $('#fileInput').click(); }); // 文件输入变化事件 $('#fileInput').change(function(e) { handleFiles(e.target.files); }); // 拖放区域事件处理 const dropArea = $('#dropArea'); dropArea.on('dragover', function(e) { e.preventDefault(); dropArea.addClass('dragover'); }); dropArea.on('dragleave', function() { dropArea.removeClass('dragover'); }); dropArea.on('drop', function(e) { e.preventDefault(); dropArea.removeClass('dragover'); if (e.originalEvent.dataTransfer.files.length) { handleFiles(e.originalEvent.dataTransfer.files); } }); // 处理选择的文件 function handleFiles(fileList) { // 清空错误消息 $('#errorMessage').hide(); // 验证每个文件 for (let i = 0; i < fileList.length; i++) { const file = fileList[i]; // 验证文件类型 const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/msword', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'text/plain']; if (!validTypes.includes(file.type)) { showError(`不支持的文件类型: ${file.name}`); continue; } // 验证文件大小 (最大10MB) if (file.size > 10 * 1024 * 1024) { showError(`文件过大: ${file.name} (最大10MB)`); continue; } // 添加到文件列表 files.push(file); } // 更新UI updateFileList(); // 启用上传按钮 if (files.length > 0) { $('#uploadBtn').prop('disabled', false); } } // 显示错误消息 function showError(message) { $('#errorMessage').text(message).show(); } // 更新文件列表UI function updateFileList() { const fileList = $('#fileList'); fileList.empty(); let totalSize = 0; files.forEach((file, index) => { totalSize += file.size; // 创建文件预览 let preview = ''; if (file.type.startsWith('image/')) { preview = `<img src="${URL.createObjectURL(file)}" alt="预览" class="file-preview">`; } else { // 根据文件类型显示不同的图标 let icon = '📄'; if (file.type.includes('pdf')) icon = '📑'; if (file.type.includes('word')) icon = '📝'; if (file.type.includes('text')) icon = '📋'; preview = `<div class="file-preview">${icon}</div>`; } const fileItem = ` <div class="file-item" id="file-${index}"> ${preview} <div class="file-info"> <div class="file-name">${file.name}</div> <div class="file-size">${formatFileSize(file.size)}</div> <div class="progress-container"> <div class="progress-bar"> <div class="progress-fill" id="progress-${index}"></div> </div> <div class="progress-info"> <span class="progress-text" id="progress-text-${index}">等待上传</span> <span class="progress-percent">0%</span> </div> </div> </div> <div class="file-actions"> <button class="action-btn cancel-btn" data-index="${index}">❌</button> </div> </div> `; fileList.append(fileItem); }); // 更新统计信息 $('#fileCount').text(files.length); $('#totalSize').text(formatFileSize(totalSize)); } // 上传按钮点击事件 $('#uploadBtn').click(function() { // 禁用上传按钮 $(this).prop('disabled', true); $('#successMessage').hide(); // 上传所有文件 files.forEach((file, index) => { uploadFile(file, index); }); }); // 上传单个文件 function uploadFile(file, index) { const fileId = `file-${index}`; // 创建FormData对象 const formData = new FormData(); formData.append('files[]', file); // 更新状态 $(`#progress-text-${index}`).text('上传中...'); // 创建XMLHttpRequest对象 const xhr = new XMLHttpRequest(); uploadRequests[fileId] = xhr; // 进度监听 xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { const percent = Math.round((e.loaded / e.total) * 100); $(`#progress-${index}`).css('width', percent + '%'); $(`#${fileId} .progress-percent`).text(percent + '%'); } }); // 完成处理 xhr.addEventListener('load', function() { if (xhr.status >= 200 && xhr.status < 300) { $(`#progress-text-${index}`).html('<span style="color:#27ae60">✓ 上传成功</span>'); } else { $(`#progress-text-${index}`).html('<span style="color:#e74c3c">✗ 上传失败</span>'); } delete uploadRequests[fileId]; // 检查所有上传是否完成 if (Object.keys(uploadRequests).length === 0) { $('#successMessage').text('所有文件上传完成!').show(); } }); // 错误处理 xhr.addEventListener('error', function() { $(`#progress-text-${index}`).html('<span style="color:#e74c3c">✗ 上传出错</span>'); delete uploadRequests[fileId]; }); // 发送请求 xhr.open('POST', 'https://httpbin.org/post', true); // 使用测试API xhr.send(formData); } // 取消上传事件 $(document).on('click', '.cancel-btn', function() { const index = $(this).data('index'); const fileId = `file-${index}`; const xhr = uploadRequests[fileId]; if (xhr) { xhr.abort(); // 终止上传 delete uploadRequests[fileId]; } // 从文件列表中移除 files.splice(index, 1); updateFileList(); // 如果没有文件了,禁用上传按钮 if (files.length === 0) { $('#uploadBtn').prop('disabled', true); } }); // 文件大小格式化函数 function formatFileSize(bytes) { if (bytes === 0) return '0 Bytes'; const k = 1024; const sizes = ['Bytes', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; } }); </script> </body> </html> ``` ## 功能特点 1. **多文件选择与拖放上传** - 支持点击选择文件或拖放文件到上传区域 - 实时显示文件预览和基本信息 2. **独立进度条显示** - 每个文件有独立的进度条 - 实时显示上传百分比 - 上传状态清晰可见(等待上传上传中、完成) 3. **文件验证** - 文件类型验证(支持图片、文档、PDF等) - 文件大小限制(最大10MB) 4. **上传管理** - 可取消单个文件的上传 - 显示已选择文件数量和总大小 - 上传完成后显示成功消息 5. **响应式设计** - 适配不同屏幕尺寸 - 美观的用户界面和交互效果 ## 实现原理 1. 使用`FormData`对象处理多文件上传 2. 通过XMLHttpRequest的`progress`事件获取上传进度 3. 为每个文件创建唯一的DOM元素和进度条 4. 使用`URL.createObjectURL()`实现文件预览 5. 存储上传请求对象,实现取消功能 ## 使用说明 1. 点击"选择文件"按钮或拖放文件到上传区域 2. 文件将显示在列表中,包括预览和大小信息 3. 点击"开始上传"按钮开始上传所有文件 4. 可以随时取消单个文件的上传 5. 上传完成后会显示成功消息 ## 相关技术参考 - 使用XMLHttpRequest的progress事件获取上传进度[^1] - 通过FormData对象处理文件上传[^1] - 使用URL.createObjectURL()实现文件预览 - 文件类型验证实现[^1] [^1]: jQuery上传文件进度条实现参考 将此代码复制到HTML文件中即可直接使用,无需额外依赖(除了jQuery)。上传功能使用了一个测试API(httpbin.org),在实际应用中需要替换为您的后端API地址。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值