使用Ajax实现上传文件的进度,要求使用JQuery来实现。完整代码
时间: 2024-02-25 08:55:21 浏览: 22
以下是使用 jQuery 实现 AJAX 文件上传进度的完整代码:
HTML 代码:
```
<input type="file" id="file">
<button id="upload-btn">上传</button>
<div id="progress"></div>
```
JavaScript 代码:
```
$(document).ready(function() {
$('#upload-btn').click(function() {
var file = $('#file')[0].files[0];
var formData = new FormData();
formData.append('file', file);
$.ajax({
url: '/upload',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() {
var xhr = new XMLHttpRequest();
xhr.upload.onprogress = function(event) {
if (event.lengthComputable) {
var percent = Math.round((event.loaded / event.total) * 100);
$('#progress').html(percent + '%');
}
};
return xhr;
},
success: function() {
$('#progress').html('上传成功');
},
error: function() {
$('#progress').html('上传失败');
}
});
});
});
```
上述代码中,我们使用了 jQuery 的 ajax() 方法来实现文件上传,并通过 xhr 属性配置了上传进度事件。需要注意的是,我们需要将 processData 和 contentType 设置为 false,以便正确处理 FormData 数据和文件类型。