jQuery使用FormData上傳文件

這段時間,一直練習在ASP.NET MVC程序中上傳文件。靜態,動態,單個或多文件上傳。

在網上有看到網友說起使用FormData來上傳,Insus.NET以爲是一個很不錯的方式。ajax


控制器中,建立兩個Action:
ide

 

代碼:url

 public ActionResult FilejQLoad()
        {
            return View();
        }

        public ActionResult Uf(HttpPostedFileBase file)
        {
            if (file.ContentLength > 0)
            {
                var fileName = Path.GetFileName(file.FileName);
                var path = Path.Combine(Server.MapPath("~/Temp"), fileName);
                file.SaveAs(path);
            }

            return new ContentResult();
        }
View Code


完成視圖:
spa

jQuery代碼:3d

$(':button').click(function () {
                var formData = new FormData($('form')[0]);
                $.ajax({
                    url: 'Uf',  
                    type: 'POST',
                    xhr: function () {  
                        return $.ajaxSettings.xhr();
                    },                   
                    success: function (data, textStatus) {
                        alert("file success uploaded.");
                        location.reload();
                    },
                    data: formData,                  
                    cache: false,
                    contentType: false,
                    processData: false
                });
            }); 
View Code


挺簡單的:
code

相關文章
相關標籤/搜索