ASP. NET 5 adventure (2): upload files, asp.net adventure
(This article is also published in my public account "dotNET daily excellent article". Welcome to the QR code on the right to follow it .)
Question: The method for processing uploaded files in ASP. NET 5 (MVC 6) is different from that before.
There are two ways to upload files in versions earlier than MVC 5.
1. access Request. Files directly to obtain HttpPostedFileBase, as shown in the following code:
[HttpPost]public ActionResult Upload(){ string path = @"D:\Temp\"; HttpPostedFileBase photo = Request.Files["photo"]; if(photo != null) photo.SaveAs(path + photo.FileName); return RedirectToAction("Index");}
2. Get HttpPostedFileBase through model binding, as shown in the following code:
[HttpPost]public ActionResult Upload(HttpPostedFileBase photo){ string path = @"D:\Temp\"; if(photo != null) photo.SaveAs(path + photo.FileName); return RedirectToAction("Index");}
For more detailed usage, refer to the CodeProject Article Uploading and returning files in ASP. net mvc.
In MVC 6, there are also two methods, except that the classes provided are different from the previous ones. Without HttpPostedFileBase, the classes are replaced by IFormFile, and some additional file information is stored in ContentDispositionHeaderValue.
1. Access IFormFile directly using Request. Form. Files, as shown in the following code:
[HttpPost]public ActionResult Upload(){ string path = @"D:\Temp\"; IFormFile photo = Request.Form.Files["photo"]; if (photo != null) { var parsedContentDisposition = ContentDispositionHeaderValue.Parse(photo.ContentDisposition); var originalName = parsedContentDisposition.FileName.Replace("\"", ""); photo.SaveAs(path + originalName); } return RedirectToAction("Index");}
As you can see, I replaced parsedContentDisposition. FileName. This is because the value of FileName contains double quotation marks. I don't know whether this is a bug or a deliberate design. I will ask an Issue later.
2. Obtain the IFormFile through model binding, as shown in the following code:
[HttpPost]public ActionResult Upload(IFormFile photo){ string path = @"D:\Temp\"; if (photo != null) { var parsedContentDisposition = ContentDispositionHeaderValue.Parse(photo.ContentDisposition); var originalName = parsedContentDisposition.FileName.Replace("\"", ""); photo.SaveAs(path + originalName); } return RedirectToAction("Index");}
In addition, Server cannot be used in MVC 6. mapPath is used to obtain the physical address corresponding to the virtual address. You can only use IHostingEnvironment. mapPath to obtain (this method is an extension method ). To use an IHostingEnvironment instance, you must inject it into the Controller (IHostingEnvironment is registered by default by the system and cannot be explicitly registered without any need ). After my experiments, we can only inject through the constructor, but not through [Activate] for Attribute injection.