文件异步上传 / 带百分比

最后更新于:2022-04-02 03:19:06

[TOC] ## 不带进度条 1. 通过 `new FormData` 可以实现文件的异步上传 ```
``` ## 文件上传显示进度 `new FormData($('#form_input')[0])` 可以把 $_POST和$_FILE 一起提交 ``` $.ajax({ url:uploadUrl + "?flag=input", type: 'POST', cache: false, data: new FormData($('#form_input')[0]), processData: false, contentType: false, beforeSend: function(){ progressJs().start(); }, success: function(result) { progressJs().end(); }, error: function (result) { }, xhr: function(){ var xhr = $.ajaxSettings.xhr(); if(onprogress && xhr.upload) { xhr.upload.addEventListener("progress" , onprogress, false); return xhr; } } }); function onprogress(evt){ if (evt.lengthComputable) { //evt.loaded:文件上传的大小 evt.total:文件总的大小 var percentComplete = Math.round((evt.loaded) * 100 / evt.total); //加载进度条,同时显示信息 progressJs().set(percentComplete); } } ``` ## 带进度条,使用bootcss 按钮 ```
var button_submit =$("button[type=submit]") $("form").submit(function(e){ button_submit.attr("disabled","disabled") var url = $(this).attr("action"); var type= $(this).attr("method"); e.preventDefault(); $.ajax({ url:url, type:type, data:new FormData(document.getElementsByTagName("form")[0]), processData:false, contentType:false, xhr: function(){ var myXhr = $.ajaxSettings.xhr(); //获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数 if(myXhr.upload){ //绑定progress事件的回调函数 myXhr.upload.addEventListener('progress',progressHandlingFunction, false); } //xhr对象返回给jQuery使用 return myXhr; }, success:function(){} }).done(function(res) { button_submit.attr("disabled",null) button_submit.html("上传") showTip(res) }).fail(function(res) { showTip(res) button_submit.html("上传") }); }); function progressHandlingFunction(e) { if (e.lengthComputable) { //e.loaded 上传大小 //e.total 文件大小 var percent = (e.loaded/e.total)*100; percent =percent.toFixed(2); button_submit.html("上传 ( "+percent+" %)") } } ```
';