MVC File Upload 1

Source: Internet
Author: User

Introduction to the MVC file upload

In this section we'll talk about how to upload files in MVC, and we'll step into it and look at them.

Upload File (i)

We add the following to the home controller in the project created by default:

        Public ActionResult UploadFile ()        {            return View ();        }        [HttpPost]        Public ActionResult uploadfile (httppostedfilebase file)        {            var fileName = file. FileName;            var FilePath = Server.MapPath (string. Format ("~/{0}", "File");            File. SaveAs (Path.Combine (FilePath, FileName));            return View ();        }

In the uploadfile view, add the following:

<form action= "/home/uploadfile" method= "post" enctype= "Multipart/form-data" >    <input type= "file" name= "File"/><br/>    <input type= "Submit" value= "Commit"/></form>

We don't have to say more about the view, just understand the following two points:

(1) in the background using HttpPostedFileBase to receive the upload file, the class is an abstract class, but in the ASP. NET Web form There is no such class, the appearance of this class is to better unit testing.

(2) The name of the file type in the view is consistent with the parameters of the background receive file.

Next we'll show you the results:

We simply uploaded an Excel file above, and we enhanced the upload by strongly typed view and model validation.

Upload File (ii)

We create the following Blogmodel class:

    public class Blogmodel    {        [Display (name = "blog name")]        [Required (errormessage = "Please enter your blog name!) ")] public        string Blogname {get; Set }        [Display (Name = "blog address")]        [Required (errormessage = "Please enter your blog address! ")] public        string Blogaddress {get; Set }        [Display (Name = "blog image")]        [Required (errormessage = "Please upload your blog image! ")]        [validatefile] public        httppostedfilebase Blogphoto {get; Set }    }

There are no attributes of the authentication file above, only the file attributes can be customized, as follows:

    public class Validatefileattribute:validationattribute    {public        override bool IsValid (object value)        {            int maxcontentlength = 1024x768 * 1024x768 * 4;            string[] allowedfileextensions = new string[] {". jpg", ". gif", ". png", ". pdf"};            var file = value as HttpPostedFileBase;            if (file = = null)                return false;            else if (! Allowedfileextensions.contains (file. Filename.substring (file. Filename.lastindexof ('. '            )))) {                errormessage = "Please upload your blog image type:" + String. Join (",", allowedfileextensions);                return false;            }            else if (file. ContentLength > Maxcontentlength)            {                errormessage = "Upload picture too large to exceed 4 megabytes:" + (maxcontentlength/1024). ToString () + "MB";                return false;            }            else                return true;        }    }

We can arbitrarily set the uploaded file size, we set to 40 trillion, in the configuration file we know maxRequestLength = 4096 default is 4 trillion, of course, we can change its default settings.

    

At this point we then modify the above method of uploading in the controller:

        [HttpPost]        Public ActionResult UploadFile (Blogmodel bmodel)        {            if (modelstate.isvalid)            {                var fileName = BModel.BlogPhoto.FileName;                var FilePath = Server.MapPath (string. Format ("~/{0}", "File");                BModel.BlogPhoto.SaveAs (Path.Combine (FilePath, FileName));                Modelstate.clear ();            }                      return View ();        }

Let's look at the effect:

What happened, the situation seems to be the reason for our file is too large, looked at the file is close to 45 trillion, and we set the 40 trillion, and then continue in the configuration file to modify the file size, but the result is the same. We continue to take a closer look at the results of the prompt, follow the prompts to find the node under the configuration file and try again, we set the Syste.webserver node to 2G:

    <security>      <requestFiltering>        <requestlimits maxallowedcontentlength= "2147483647" >        </requestLimits>      </requestFiltering>    </security>

The result is good, check also have encountered similar problems of people, seemingly only to give a result, but did not give explanations, why in the httpRuntime set not, but some of these settings are correct, what is the reason? Finally found the answer:

(1) In IIS 5 and IIS 6, the default file upload is a maximum of 4 megabytes, and when the uploaded file size exceeds 4 megabytes, you get an error message, but we set the file size by setting it down.

<system.web>  

(2) In IIS 7, the default file upload of up to 28.6 trillion, when more than its default setting size, also get error message, but we can set the file upload size.

<system.webServer>  <security>    <requestFiltering>      <requestlimits Maxallowedcontentlength= "2147483647"/>    </requestFiltering>  </security></ System.webserver>

"By analogy, the individual feels that it is possible that the file upload size above IIS 7+ is set by the IIS 7来 as above."

Although we verify it on the server side, we feel that this is still not safe, and we continue to verify the type and size of the images it uploads on the client.

(1) Use the strongly typed view to give the View code:

<style type= "Text/css" >. field-validation-error {color:red; }</style><form id= "Uploadfilesub" action= "/home/uploadfile" method= "post" enctype= "Multipart/form-data"                > <fieldset> <legend></legend> <ul class= "Lifile" > <li> @Html. labelfor (M = m.blogname) <br/> @Html. textboxfor (M = m.blogname, new {Maxleng                th =) @Html. validationmessagefor (M = m.blogname) </li> <li> @Html. labelfor (M = m.blogaddress) <br/> @Html. textboxfor (M = m.blogaddress, new {            maxlength = $) @Html. Validationmessagefor (M = m.blogaddress) <br/> </li>  <li> @Html. labelfor (M = M.blogphoto) @Html. textboxfor (M = M.blogphoto, New {type = "file"}) @Html. validationmessagefor (M + = m. Blogphoto) <span id= "Warning" style= "color:red;font-size:large;"            ></span> </li> <li> <input type= "Submit" value= "Submission"/> </li> </ul> </fieldset></form>

(2) Use the script to get the upload file size:

    function GetFileSize (Fileid) {        var fileSize = 0;        FileSize = $ ("#" + Fileid) [0].files[0].size;        FileSize = filesize/1048576;        return fileSize;    }

(3) Get the file name according to the uploaded path:

    function Getnamefrompath (strFilePath) {        var objre = new RegExp (/([^\/\\]+) $/);        var strName = objre.exec (strFilePath);        if (StrName = = null) {            return null;        }        else {            return strname[0];        }    }

(4) When a file is changed, the change event is triggered to verify its file type and file size:

        $ ("#BlogPhoto"). Change (function () {var file = Getnamefrompath ($ (this). Val ());                if (file = null) {var errors = $ (document). Find (". Field-validation-error");                        $.each (Errors, function (k, v) {if ($ (v). attr ("data-valmsg-for") = = = = "Blogphoto") {                    $ (v). Hide ();                }                });                var extension = File.substr ((File.lastindexof ('. ') + 1));                    Switch (extension) {case ' jpg ': Case ' png ': Case ' gif ':                        Case ' PDF ': Filetypebool = false;                    Break                Default:filetypebool = true; }} if (Filetypebool) {$ ("#warning"). html ("Upload only files with the extension jpg,png,gif,pdf!                ");            return false; } else {var size = GetfilesiZe (' Blogphoto ');                    if (Size > 4) {filesizebool = true; $ ("#warning"). html ("Upload file already exceeds 4 megabytes!")                ");                } else {filesizebool = false; }            }        });

(5) Verify the file when you click the Submit button:

        $ ("#uploadFileSub"). Submit (function () {            $ ("input[type= ' text ']"). each (function (k, v) {                if ($ (v). Length) {                    $ (v). Siblings ("span"). Hide ();                }            );            if (Filetypebool | | filesizebool) {                return false;            }        });

"Note" The above for verification is not too complete, but the basic shelf has been given.

Let's take a complete demonstration of the whole process.

The above we have been using the pure HTML code, of course, can also use the MVC extension method to do, as follows (the final rendering or form, essentially the same, do not do too much discussion)

@using (Html.BeginForm ("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"})) {  <input Type= "File" id= "file" name= "file"/> <input type= "Submit" value= "Submit"/>}
Conclusion

In this section we describe in more detail how files are uploaded in MVC, but one thing we haven't talked about is the use of streams to insert images like our above into a database. For the upload can refer to the park friend Insus.net on this use stream to upload.

MVC File Upload 1

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.