Simple File uploading in ASP.NET MVC:
As given in the following code, create form with the upload box and don’t forget to include the enctype in the form tag, which represents the content type of the request.
Note: enctype="multipart/form-data" is mandatory because it represents the file type.
- <form action="/sample/upload" method="post" enctype="multipart/form-data">
- Sample Upload:<br/>
-
- <input type="file" name="file" id="file" />
-
- <input type="submit" value="Upload" />
-
- </form>
In controller page get the file from the client request using Request instance example: Request.Files["file"];
- [HttpPost]
-
- public ActionResult Upload()
- {
-
- string location = @"e:\location\";
-
- HttpPostedFileBase file= Request.Files["file"];
-
- if(file!= null && file.ContentLength > 0)
- {
-
- var fileName = Path.GetFileName(file.FileName);
-
- file.SaveAs(Path.Combine(location, fileName));
-
- }
-
- return RedirectToAction("Index");
-
- }