同步上传文件和异步上传文件

两者最大的区别就是:表单上传过程中,整个页面就刷新了;而异步上传就可以达到只刷新局部位置!
参考文章地址:[https://www.cnblogs.com/fengxuehuanlin/p/5311648.html]

1 异步上传:

1.1html

image.png

1.2 js脚本

function uploadFiles() {
            if (!$('#fileUpload').val()) return;  

            $("#uploadInfo").html("");
            $.ajaxFileUpload({
                url: "@Url.Action("FileToLoad", "Card")",//用于文件上传的服务器端请求地址
                secureuri: false,//一般设置为false
                fileElementId: "fileUpload",//文件上传标签元素的Id
                dataType: "json", //返回值类型,一般设置为json
                type: "POST",//请求方式
                success: function (data, status) //服务器响应成功后,处理函数
                {
                    if (data.Success) {                      
                        $("#FileIdhidden").val(data.ObjectId);
                        $("#uploadInfo").html("上传成功,共计:"+ data.Count+"条");
                    } else {
                        alert("上传失败:" + data.Message);
                    }
                },
                error: function (data, status, e) //服务器响应失败后,处理函数
                    Oudao.ShowMessage(false, "上传文件失败,请确认上传文件是否存在或文件格式是否有效!");
                },
                onComplete: function (filename, response) {//请求完成后,处理函数
                    $('#fileUpload').val("");
                    $("#uploadInfo").html("");
                }
            });
           
        }

1.3后端接口

对上传文件的处理

[HttpPost]
        public ActionResult FileToLoad()
        {
            JsonResultData result = new JsonResultData();
            result.Success = false;
            result.Message = "上传文件失败!";

            if (Request.Files.Count > 0)
            {
                HttpPostedFileBase filetoLoad = Request.Files[0];

                string newFileName = Guid.NewGuid().ToString("N");
                string path = Server.MapPath(ConstString.FileLoadPath.CardFileUpload); //临时目录
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }

                string filePath = Path.Combine(path, newFileName);

                filetoLoad.SaveAs(filePath);
                try
                {
                    var lines = System.IO.File.ReadLines(filePath);
                    result.Success = true;
                    result.Message = "ok.";
                    result.ObjectId = newFileName;
                    result.Count = lines.Count();
                }
                catch (Exception ex)
                {
                    result.Success = false;
                    result.Message = "读取文件失败:" + ex.Message;
                    System.IO.File.Delete(filePath);
                }
            }

            var content = SerializeHelper.GetJson(result);

            return Content(content, "text/html");
        }

注:表单提交中的 "button"按钮,不需要type类型,或者type="Submit"
[图片上传中...(image.png-ac9a5e-1575880787952-0)]

2 同步上传
[https://www.cnblogs.com/fengxuehuanlin/p/5311648.html]

你可能感兴趣的:(同步上传文件和异步上传文件)