IT wheel series (IV)-use Jquery + formdata object to upload files, jqueryformdata
Preface
The following controls are generally used to upload files in MVC:
1 View Code
Method 1: Use form upload
Front-end code:
<Div> <form action = "/FileUpload/UploadFile" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "file" /> <br/> <input type = "submit" value = "submit"/> </form> </div>
View Code
On the front-end interface, note that when using form to submit data, the control on our page must have the name attribute. Otherwise, no data is received in the background.
Background code:
1 [HttpPost] 2 public ActionResult UploadFile () {3 try 4 {5 var files = Request. files; 6 foreach (string item in files) 7 {8 // you can upload multiple files 9 var file = Files [item]; 10 var fileName = file. fileName; 11 var filePath = Server. mapPath (string. format ("~ /{0} "," File "); 12 // determine whether the path exists 13 if (! Directory. exists (filePath) 14 {15 // create path 16 Directory. createDirectory (filePath); 17} 18 // save file 19. saveAs (Path. combine (filePath, fileName); 20} 21} 22 catch (Exception ex) 23 {24 throw; 25} 26 return View ("Index"); 27}
View Code
The file is saved to the specified directory.
Method 2: Use Jquery + formdata object
The formdata object uploads files in another form method. Submit through juqery instead of the default action of form.
1 Front-end view
1 public ActionResult Upload () 2 {3 // both files and forms can process and parse uploaded files and data in the first Upload mode. 4 var files = Request. files; 5 var form = Request. form; 6 // do something here 7 8 // return the josn object 9 var obj = new10 {11 success = 112}; 13 return Json (obj); 14}
Backend receiving code
Postscript
I typed code in my hand. When I wrote this blog, I suddenly found that I used to upload files that I knew. Now I only found that I only thought it was; however, I found that I missed a lot of knowledge points when I typed the Code. For example, the name attribute is required for form upload. This knowledge point is available only after reading articles from other bloggers.
This is a mistake: the eyes are low.
I suggest using this blog to spur myself.