formdata 上传图片+进度条

记得引入jquery

 

    //上传进度回调函数:  
        function progressHandlingFunction(e) {
            if (e.lengthComputable) {
                $('progress').attr({ value: e.loaded, max: e.total }); //更新数据到进度条  
                var percent = e.loaded / e.total * 100;
                $('#progress').html(e.loaded + "/" + e.total + " bytes. " + percent.toFixed(2) + "%");
            }
        }


            $("#upFilebtn").click(function () {
                //判断文件类型
                var file = $("#AjaxFileData")[0].files[0];
                var imgType = (file.name.substr(file.name.lastIndexOf("."))).toLowerCase();
                if (imgType != ".jpg" && imgType != ".gif" && imgType != ".jpeg" && imgType != ".png") {
                    alert("您上传图片的类型不符合(.jpg|.jpeg|.gif|.png)!");
                    return false;
                }
                if (($("#AjaxFileData")[0].files[0].size / 1024) > (5 * 1024)) {
                    alert("上传图片不得大于 5M");
                    return;
                }
                var formData = new FormData();
                formData.append("username", "formName");
                formData.append("file", file);
                $.ajax({
                    url: '喂喂改一下',
                    type: 'post',
                    data: formData,
                    xhr: function () { //获取ajaxSettings中的xhr对象,为它的upload属性绑定progress事件的处理函数  
                        myXhr = $.ajaxSettings.xhr();
                        if (myXhr.upload) { //检查upload属性是否存在  
                            //绑定progress事件的回调函数  
                            myXhr.upload.addEventListener('progress', progressHandlingFunction, false);
                        }
                        return myXhr; //xhr对象返回给jQuery使用  
                    },
                    processData: false,
                    contentType: false,
                    success: function (msg) {
                   
                    alert('不谈了');
                    }
                });
            });

html:

  <input id="AjaxFileData" type="file" >

  <input  type="button" id="upFilebtn" >

上传进度:<progress></progress><br/>  
    <p id="progress">0 bytes</p>  
    <p id="info"></p>

server:

  string fileDir = HttpContext.Current.Server.MapPath("~/uploadfile/Do");

       HttpPostedFile file = context.Request.Files["file"];

    file.SaveAs(Path.Combine(fileDir, fileName));

好人甲 : https://www.cnblogs.com/tyqing/p/5995538.html

原文地址:https://www.cnblogs.com/j2ee-web-01/p/9269539.html