要实现文件上传进度条效果,可以使用jQuery和HTML5的File API,具体步骤如下:
步骤一:HTML代码
首先,在HTML页面中添加一个表单元素,用于选择文件。例如:
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="file"><br>
<input type="submit" value="Upload File">
</form>
步骤二:jQuery代码
- 给表单元素绑定submit事件,阻止表单默认提交行为,使用ajax方式提交表单数据。
$('#uploadForm').submit(function(event) {
event.preventDefault(); // 阻止表单默认提交
// 使用ajax方式提交表单数据
});
- 在ajax提交之前,先获取文件信息,使用FormData对象进行封装。使用ajax提交FormData,实现文件上传。
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function(data) {
console.log('Success: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
}
});
- 实现上传进度条效果。jQuery使用XHR对象实现ajax,可以利用其提供的progress事件,获得上传进度信息,从而实现实时更新进度条。
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
console.log('Progress: ' + percentComplete + '%');
// 更新进度条
}
}, false);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() { // 返回jquery提供的XHR对象,用于监听progress事件
return xhr;
},
success: function(data) {
console.log('Success: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
}
});
- 完整的jQuery代码示例:
$('#uploadForm').submit(function(event) {
event.preventDefault(); // 阻止表单默认提交
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
console.log('Progress: ' + percentComplete + '%');
// 更新进度条
}
}, false);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() { // 返回jquery提供的XHR对象,用于监听progress事件
return xhr;
},
success: function(data) {
console.log('Success: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
}
});
});
示例说明
在上面的jQuery代码示例中,我们使用了ajax进行文件上传,并利用XHR对象的progress事件实现了上传进度条效果。
为了更直观地演示该效果,我们可以在页面上添加一个进度条元素,如下:
<div id="progressBar"></div>
然后,在progress事件中更新进度条的宽度即可:
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
console.log('Progress: ' + percentComplete + '%');
// 更新进度条
$('#progressBar').css('width', percentComplete + '%');
}
具体实现可以参考下面的示例:
示例一
一个简单的文件上传进度条示例,使用Bootstrap样式美化进度条。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery File Upload Progress Demo</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<style>
#progressBar {
height: 20px;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
-webkit-transition: width .4s ease-in-out;
-o-transition: width .4s ease-in-out;
transition: width .4s ease-in-out;
}
</style>
</head>
<body>
<div class="container">
<h2>jQuery File Upload Progress Demo</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="file">Choose File:</label>
<input type="file" name="file" id="file" class="form-control">
</div>
<input type="submit" value="Upload File" class="btn btn-primary">
</form>
<div class="progress">
<div id="progressBar" class="progress-bar"></div>
</div>
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$('#uploadForm').submit(function(event) {
event.preventDefault(); // 阻止表单默认提交
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
var xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
console.log('Progress: ' + percentComplete + '%');
$('#progressBar').css('width', percentComplete + '%');
}
}, false);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() { // 返回jquery提供的XHR对象,用于监听progress事件
return xhr;
},
success: function(data) {
console.log('Success: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
示例二
一个带有取消上传按钮和上传完成提示的文件上传进度条示例,使用Bootstrap样式美化进度条。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>jQuery File Upload Progress Demo</title>
<link href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css" rel="stylesheet">
<style>
#progressBar {
height: 20px;
background-color: #f5f5f5;
border-radius: 4px;
-webkit-box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
box-shadow: inset 0 1px 2px rgba(0,0,0,.1);
-webkit-transition: width .4s ease-in-out;
-o-transition: width .4s ease-in-out;
transition: width .4s ease-in-out;
}
#cancelUploadButton {
margin-left: 10px;
}
#uploadCompleteMessage {
color: #005500;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<h2>jQuery File Upload Progress Demo</h2>
<form id="uploadForm" action="upload.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="file">Choose File:</label>
<input type="file" name="file" id="file" class="form-control">
</div>
<input type="submit" value="Upload File" class="btn btn-primary">
<button id="cancelUploadButton" type="button" class="btn btn-default">Cancel</button>
</form>
<div class="progress">
<div id="progressBar" class="progress-bar"></div>
</div>
<div id="uploadCompleteMessage"></div>
</div>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
var xhr;
$('#uploadForm').submit(function(event) {
event.preventDefault(); // 阻止表单默认提交
var formData = new FormData();
formData.append('file', $('#file')[0].files[0]);
xhr = $.ajaxSettings.xhr();
xhr.upload.addEventListener('progress', function(event) {
if (event.lengthComputable) {
var percentComplete = Math.round(event.loaded / event.total * 100);
console.log('Progress: ' + percentComplete + '%');
$('#progressBar').css('width', percentComplete + '%');
}
}, false);
xhr.addEventListener('load', function(event) {
if (event.target.status === 200) {
console.log('Upload complete.');
$('#cancelUploadButton').hide();
$('#uploadCompleteMessage').html('Upload Complete!').show();
}
}, false);
xhr.addEventListener('error', function(event) {
console.error('Error: ' + event.target.status, event.target.statusText);
}, false);
xhr.addEventListener('abort', function(event) {
console.log('Upload cancelled.');
}, false);
$.ajax({
url: 'upload.php',
type: 'POST',
data: formData,
processData: false,
contentType: false,
xhr: function() { // 返回jquery提供的XHR对象,用于监听progress事件
return xhr;
},
success: function(data) {
console.log('Success: ' + data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.error('Error: ' + textStatus, errorThrown);
}
});
});
$('#cancelUploadButton').click(function() {
if (xhr) {
xhr.abort(); // 取消上传
console.log('Upload cancelled.');
}
});
</script>
</body>
</html>
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:jQuery实现简单的文件上传进度条效果 - Python技术站