1. Download Ajaxfileupload.js
2. Create the following method within the controller
File Upload public actionresult uploadfile (httppostedfilebase file) { if (file = = null) { return Json ( New {result = "false", errormsg= "file does not exist"}, "text/html"); } String fileName = "~/uploadfiles/" + DateTime.Now.ToString ("yyyymmddhhssmm") + path.getfilename (file. FileName); var physicsfilename = Server.MapPath (fileName); Try { file. SaveAs (physicsfilename); Return Json (New {result = "true", Imgurl = FileName}, "text/html"); } catch (Exception ex) { return Json (new {result = "false", ErrorMsg = ex. Message}, "text/html"); } }
3, write the following JS in the front-end, need to introduce jquery and Ajaxfileupload.js
<script type= "Text/javascript" > Function Ajaxfileuploads () {$ ("#loading"). Ajaxstart (function () {$ (this). Show (); }). Ajaxcomplete (function () {$ (this). Hide (); }); $.ajaxfileupload ({url: '/user/uploadfile ',//Background processing-controller/action SECUREURI:FA LSE, Fileelementid: ' Filetoupload ',//Upload file Name property dataType: ' JSON ', type: ' P Ost ', Success:function (data, status) {alert (data.result); if (Data.result = = = "true") {//successfully after the background file path is assigned to the exception control, easy to submit to the background alert (Data.imgurl); $ (". Imgurl"). Val (Data.imgurl); } else if (Data.result = = = "false") {alert (data.errormsg); }}, Error:function (data, status, E) {alert (e); }}) return false; } $ (document). Ready (function () {$ (". Btnupload"). Click (function () {ajaxfileuploads (); }); }); </script>
4. The code in view
<div> profile Picture: @Html. hiddenfor (M = m.imgurl, new {@class = "Imgurl"}) //strong type binding <input type= "File" Id= "Filetoupload" name= "file"/><input type= "button" class= "Btnupload" value= "upload"/> //Upload control and upload button <span id= "Loading" style= "Display:none;" > Please wait </span> //wait for prompt </div>
ASP. NET MVC4 Asynchronous File upload