If you only have the ASP.net Web forms background instead of learning asp.net mvc, I think your first experience may be that the service-side controls that have made your programming enjoyable are driving the crane West. FileUpload is one of them, and the absence of this control brings us some minor problems. This article mainly says how to upload files in asp.net mvc, and then how to download the uploaded files from the server.
In Web Forms, when you drag a FileUpload control to the designer, you may not notice that adding an extra attribute to the form tag in the generated HTML enctype= "Multipart/form-data". The FileUpload control itself becomes <input type= "file"/>, and in MVC view there are many ways to do the same, the first HTML is as follows:
<form action= "/" method= "POST" enctype= "Multipart/form-data" >
<input type= "File" Name= "FileUpload1"/><br/>
<input type= "Submit" name= "submit" id= "Submit" value= "Upload"/>
</form>
Note that the form label already includes the enctype tag, and the method property is set to "post" so that it does not have to be set more than the default commit by HTTP GET. In this way, using the Html.BeginForm () extension method generates the same HTML as the above:
<%
using (Html.BeginForm ("", "Home", FormMethod.Post, new {enctype= "Multipart/form-data"}))
{%>
<input type= "File" Name= "FileUpload1"/><br/>
<input type= "Submit" name= "submit" id= "Submit" value= "Upload"/>
<%}%>
Now we can browse the local file and then submit the file to the server side via the Upload submit button, and the next step is to process the uploaded file on the server side, and when using the FileUpload control, You can easily see if the file is uploaded through the FileUpload HasFile method. But in asp.net mvc it seems not so convenient, you will be closer to the original HTTP, however, an extension method can handle these:
public static bool HasFile (this httppostedfilebase file)
{
return (file!= null && file. ContentLength > 0)? True:false;
}
When you see the corresponding controller class code, you will find that the request object exists as an attribute of the httprequestbase type. Httpreuqestbase is actually an encapsulation of the HTTP request, which leaks a lot of attributes, including the Files collection (actually a collection of httpfilecollectionbase), Each element in the collection is a collection of httppostedfilebase, and the extension method is used to ensure that the uploaded file exists. In fact, this works in accordance with the Fileupload.hasfile () method.
It's really easy to use in controller action:
public class Homecontroller:controller
{
Public ActionResult Index ()
{