HTML代码
<div class="progress">
<div id="progress" class="progress-bar progress-bar-striped active"
role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width: 0%">
</div>
</div>
<form id="my_form" action='upload_test.php' method='post' enctype='multipart/form-data'>
<div class="form-group form-inline">
<label for="my_name" class="control-label">名称</label>
<input type="text" class="form-control" id="my_name" name="my_name" required/>
</div>
<div class="form-group form-inline">
<label for="my_file" class="control-label">文件</label>
<input type="file" class="form-control" id="my_file" name="my_file" />
</div>
<div class="form-group">
<button type="button" class="btn btn-primary" onclick="upload();">提交</button>
</div>
</form>
js代码
function upload()
{
var formData = new FormData();
formData.append("my_name", $('#my_name').val());
formData.append("my_file", $('#my_file')[0].files[0]);
// var formData = new FormData($('#my_form')[0]);
var xhr = new XMLHttpRequest();
xhr.upload.addEventListener("progress", progressHandler, false);
xhr.addEventListener("load", completeHandler, false);
xhr.open("POST", "upload_test.php");
xhr.onreadystatechange = function() {
if(xhr.readyState == 4 && xhr.status == 200) {
// alert(xhr.responseText);
}
}
xhr.send(formData);
}
function progressHandler(event)
{
var percent = parseInt((event.loaded / event.total) * 100);
percent = percent + '%';
$('#progress').width(percent);
$('#progress')[0].innerHTML = percent;
}
function completeHandler()
{
$('#progress')[0].innerHTML = "已上传";
}