咨询:如何通过JS/jQuery实现文件上传时加载器的显示与隐藏
当然有合适的方案啦!针对大文件上传时用户看不到进度的问题,我们可以用JavaScript或者jQuery来监听上传的开始、结束甚至中间的进度状态,下面给你详细的实现思路和代码示例:
先给表单加个标识方便操作
首先给你的表单和状态提示元素加个ID,这样更容易选中和操作:
<form id="uploadForm" method="POST" enctype="multipart/form-data"> <input type="file" name="pic" accept="image/*"> <button type="submit">Salva</button> </form> <!-- 用来显示上传状态的元素 --> <div id="uploadStatus"></div>
原生JavaScript实现方案
我们可以通过阻止表单默认提交行为,手动用XMLHttpRequest发送请求,这样就能监听一系列上传相关事件:
const uploadForm = document.getElementById('uploadForm'); const statusDisplay = document.getElementById('uploadStatus'); uploadForm.addEventListener('submit', function(e) { // 阻止默认的表单刷新提交 e.preventDefault(); // 上传开始:显示加载提示 statusDisplay.textContent = '上传中,请稍候...'; statusDisplay.style.color = '#2196F3'; // 包装表单数据 const formData = new FormData(this); const xhr = new XMLHttpRequest(); // 配置请求地址(如果表单没写action,默认就是当前页面) xhr.open('POST', this.action || window.location.href); // 【可选】监听上传正式开始的事件 xhr.addEventListener('loadstart', function() { console.log('上传流程正式启动'); }); // 【推荐】监听上传进度,给用户实时反馈 xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { const progressPercent = Math.round((e.loaded / e.total) * 100); statusDisplay.textContent = `上传中:${progressPercent}%`; } }); // 上传结束(成功/失败都会触发) xhr.addEventListener('loadend', function() { // 先判断请求是否成功 if (xhr.status >= 200 && xhr.status < 300) { statusDisplay.textContent = '上传完成!'; statusDisplay.style.color = '#4CAF50'; // 重置表单 uploadForm.reset(); } else { statusDisplay.textContent = '上传失败,请重试'; statusDisplay.style.color = '#F44336'; } }); // 发送请求 xhr.send(formData); });
jQuery实现方案
如果你习惯用jQuery,也可以通过$.ajax来实现,核心逻辑和原生类似,只是写法更简洁:
$('#uploadForm').submit(function(e) { e.preventDefault(); const $status = $('#uploadStatus'); // 上传开始的操作 $status.text('上传中,请稍候...').css('color', '#2196F3'); $.ajax({ url: $(this).attr('action') || window.location.href, type: 'POST', data: new FormData(this), // 这两个参数必须设置,不然jQuery会错误处理FormData processData: false, contentType: false, // 上传开始前的回调 beforeSend: function() { console.log('即将开始上传'); }, // 自定义XHR对象,用来监听进度 xhr: function() { const xhr = new XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e) { if (e.lengthComputable) { const progress = Math.round((e.loaded / e.total) * 100); $status.text(`上传中:${progress}%`); } }); return xhr; }, // 上传成功的回调 success: function() { $status.text('上传完成!').css('color', '#4CAF50'); $('#uploadForm')[0].reset(); }, // 上传失败的回调 error: function() { $status.text('上传失败,请重试').css('color', '#F44336'); }, // 上传结束(无论成功失败都会触发) complete: function() { console.log('上传流程结束'); } }); });
关键事件说明
- 上传开始:可以在表单的
submit事件、beforeSend(jQuery)或者loadstart(原生XHR)里处理,比如显示加载动画或提示。 - 上传进度:通过
xhr.upload.progress事件可以实时获取已上传的字节数和总字节数,用来做进度条非常合适。 - 上传结束:
loadend(原生)或complete(jQuery)会在请求完成后触发,不管成功还是失败;如果需要区分成功和失败,就用success/error或者判断XHR的状态码。
内容的提问来源于stack exchange,提问作者aletede91
相关产品推荐
相关产品推荐

