1、首先,需要引用jquery两个文件
jquery-2.0.0.min.js和jquery.form.js
2、然后编写html代码如下
<div style="font-size: 20px;color: #888;border: 1px solid #ccc;height: 98px;line-height: 98px;width: 100px;cursor: default;text-align: center;display: inline-block;position: relative;float: left;">
<div class="progressDiv" style="font-size: 12px; line-height: 20px; position: absolute; top: 40px; left: 0px; width: 100%; height: 20px; background: rgb(204, 204, 204);">
<span style="z-index:2;text-align:center;color:#fff;position: absolute;top: 0;left:0px;width:100%;height:20px;">61%</span>
<div class="progressValueDiv" style="z-index: 1; text-align: center; color: rgb(255, 255, 255); position: absolute; top: 0px; left: 0px; width: 61%; height: 20px; background: rgb(10, 173, 255);"></div>
</div>
<span>+</span>
<form id="myform" method="POST" enctype="multipart/form-data" onsubmit="return false;">
<input name="file" type="file" style="">
</form>
</div>
3、然后就是,调用ajaxSubmit方法
$("body").on("change", "#file", function () {
if ($(this).val() != "") {
$("#myform").ajaxSubmit({
url: =url,
type: 'post',
dataType: "json",
beforeSubmit: function () {
//设置进度条
$(".progressDiv").show();
},
uploadProgress: function (e, r, t, s) {
//进度达到百分之百后才会调用后台接口
var value = parseInt((r / t) * 100);
$(".progressDiv span").show().html(value + "%");
$(".progressDiv .progressValueDiv").css({ "width": value + "%" });
},
success: function (d) {
},
error: function (d) {
}
});
}
});
注:
1)ajaxSubmit会多出一个OPTIONS请求,为什么会出现呢?
属于调用前探测请求,如果options返回的状态是200,则认为请求是安全可靠的
【欢迎咨询】