The content of this article is about the code for Ajax uploading files and displaying the progress bar of the file upload process. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
I am learning ASP.NET MVC recently, and I happened to upload files and record them.
In addition to jQuery, the front end also uses Bootstrap and Layer.
Form in HTML page:
<form class="form-horizontal" id="vform" action=""> <div class="form-group"> <label class="col-sm-3 control-label">资源名称:</label> <div class="col-sm-8"> <input name="name" type="text" class="form-control" id="name" /> </div> </div> <div class="form-group"> <label class="col-sm-3 control-label">请选择本地资源:</label> <div class="col-sm-8"> <input name="file" type="file" class="form-control" id="file" /> <div class="progress"> <div class="progress-bar" id="progress-bar"></div> </div> </div> </div> <div class="form-group"> <div class="col-sm-4 col-sm-offset-3"> <input class="btn btn-primary" id="submit" value="确认上传" /> </div> </div> </form>
JavaScript code:
<script> $("#submit").click(function () { var formData = new FormData(document.getElementById("vform")); $.ajax({ type: "POST", url: "@Url.Action("DoAdd")", data: formData, processData: false, contentType: false, error: function (data) { layer.msg('上传失败', { icon: 2, time: 1000 //1秒关闭(如果不配置,默认是3秒) }); }, success: function (data) { if (data.code == 1) { layer.msg('上传成功', { icon: 1, time: 1000 //1秒关闭(如果不配置,默认是3秒) }, function () { parent.location.reload(); }); } else { layer.msg(data.msg, { icon: 2, time: 1000 //1秒关闭(如果不配置,默认是3秒) }); } }, xhr: function () { myXhr = $.ajaxSettings.xhr(); if (myXhr.upload) { //检查upload属性是否存在 //绑定progress事件的回调函数 myXhr.upload.addEventListener('progress', progressHandlingFunction, false); } return myXhr; //xhr对象返回给jQuery使用 } }); }); function progressHandlingFunction(event) { var loaded = Math.floor(100 * (event.loaded / event.total)); //已经上传的百分比 $("#progress-bar").html(loaded + "%").css("width", loaded + "%"); }</script>
Related recommendations:
js implementation of gzip decompression code implementation
The above is the detailed content of Code for Ajax uploading files and displaying the progress bar of the file upload process. For more information, please follow other related articles on the PHP Chinese website!