前言
文件上传如果加上进度条会有更好的用户体验(尤其是中大型文件),本文使用
Nodejs 配合前端完成这个功能。前端我们使用
FormData 来作为载体发送数据。效果
前端部分
HTML 部分 和 Js 部分
<input type="file" id="file" />
<!-- 进度条 -->
<progress id="progress" value="0" max="100"></progress>
// 获取 input file 的 dom 对象
const inputFile = document.querySelector('#file');// 监听 change 事件
inputFile.addEventListener('change', function() {
// 使用 formData 装载 file
const formData = new FormData();
formData.append('file', this.files[0]);
// 上传文件
upload(formData);
})
下面我们实现 upload 方法。
使用 XMLHttpRequest 的方式
const upload = ( formData ) => {
const xhr = new XMLHttpRequest();
// 监听文件上传进度
xhr.upload.addEventListener('progress', function(e) {
if (e.lengthComputable) {
// 获取进度
const progress = Math.round((e.loaded * 100) / e.total); document.querySelector('#progress').setAttribute('value', progress);
}
},false);
// 监听上传完成事件
xhr.addEventListener('load', ()=>{
console.log(':smile:上传完成')
}, false);
xhr.open('post', 'http://127.0.0.1:3000/upload');
xhr.send(formData);
}
使用 jQuery 的 ajax 上传
jQuery 目前的使用量依然庞大,那么使用 jQuery 的 ajax 如何监听文件上传进度呢:
const upload = ( formData ) => {
$.ajax({
type: 'post',
url: 'http://127.0.0.1:3000/upload',
data: formData,
// 不进行数据处理和内容处理
processData: false,
contentType: false,
// 监听 xhr
xhr: function() {
const xhr = $.ajaxSettings.xhr();
if (xhr.upload) {
xhr.upload.addEventListener('progress', e => {
const { loaded, total } = e;
var progress = (loaded / total) * 100;
document.querySelector('#progress').setAttribute('value', progress);
},
false
);
return xhr;
}
},
success: function(response) {
console.log('上传成功');
}
});
}使用 axios 上传并监听进度
axios 使用量非常大,用它监听文件上传更简单,代码如下:
const upload = async ( formData ) => { let config = {
// 注意要把 contentType 设置为 multipart/form-data









