(This article also published in my public number "dotnet daily Essence article", Welcome to the right QR code to pay attention to. )
Preface: The way to process and upload files in ASP. NET 5 (MVC 6) is different.
There are two ways to upload files in versions prior to MVC 5.
1, access the request.files directly to get the HttpPostedFileBase, as shown in the following code:
[HttpPost] Public ActionResult Upload () { string@ "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");}
More detailed usage can be found in CodeProject's article "uploading and returning files in ASP."
There are also two ways in MVC 6, except that the classes provided are different from the previous ones, without HttpPostedFileBase, instead of iformfile, and additional file information is placed in the 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 \, ); Photo. SaveAs (path + originalname); } return redirecttoaction ( "Index" );}
As you can see, I have a replacement deal with Parsedcontentdisposition.filename. This is because the property value of filename will be preceded by double quotation marks. I do not know whether this is a bug or intentional design, after a while to mention a issue ask.
2, get iformfile through model binding, as shown in the following code:
[HttpPost] Public ActionResult Upload (iformfile photo) { string@ "D:\Temp\"; if (photo! = null) { var parsedcontentdisposition = contentdispositionheadervalue.parse (photo. contentdisposition); var originalname = parsedContentDisposition.FileName.Replace ("\""" "); Photo. SaveAs (path + originalname); } return Redirecttoaction ("Index");}
Also, it is important to note that in MVC 6 it is not possible to get the physical address of the virtual address with Server.MapPath, which can only be obtained by Ihostingenvironment.mappath (this method is an extension method). To use an instance of ihostingenvironment, it must be injected into the controller (Ihostingenvironment is registered by the system by default and cannot be explicitly registered). Through my experiments, I can only inject through the constructor, but not through [Activate] to attribute injection.
ASP. 5 Adventure (2): Uploading Files