asp.net MVC file Upload Tutorial (i) _ Practical skills

Source: Internet
Author: User
Tags file upload

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

Upload File (i)
we add the following under 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 ();
  }

Add the following in the UploadFile view:

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

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

(1) in the background using HttpPostedFileBase to receive uploaded files, the class is an abstract class, but in the ASP.net Web form does not have this class, the appearance of this class is for better unit testing.

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

Next we'll show you the results:

The above we simply uploaded an Excel file, below we use strongly typed view and model validation to enhance the upload.

Upload File (ii)
we create the following Blogmodel classes:

 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 picture")]
  [Required (errormessage = "Please upload your blog picture!) ")]
  [validatefile] public
  httppostedfilebase Blogphoto {get; Set }
 }

The attributes of the above unauthenticated files can only be customized to the file attributes, as follows:

 public class Validatefileattribute:validationattribute
 {public
  override bool IsValid (object value)
  {
   int maxcontentlength = 1024 * 1024 * 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 picture type:" + String. Join (",", allowedfileextensions);
    return false;
   }
   else if (file. ContentLength > Maxcontentlength)
   {
    errormessage = "Upload picture too large, not more than 4 trillion:" + (maxcontentlength/1024). ToString () + "MB";
    return false;
   }
   else return
    true;
  }
 }

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


At this point we then modify the above upload method 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:

It seems that the reason for our file is too large, looked at the file is close to 45 trillion, and we set a 40 trillion, so continue to modify the file size in the configuration file, but the result is the same. We continue to take a closer look at the results of the prompts, according to 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 results are good, check the check also have encountered similar problems, seemingly only to give a result, but did not give an explanation, why not set in the HttpRuntime, but some such settings are correct, this is what the reason? Finally found the answer:

(1) In IIS 5 and IIS 6, the default file upload maximum of 4 megabytes, when the uploaded file size of more than 4 megabytes, you will get an error message, but we set the file size by such as down.

<system.web>
  
 

(2) In IIS 7, the default file upload maximum of 28.6 megabytes, when the default size is exceeded, the same 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 may be in IIS 7+ above all by setting the file upload size as described above in IIS 7来"

Although we verify it on the server side, but we don't think it's safe, we continue to verify the type and size of the pictures it uploads on the client.

(1) Using a 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 =&gt ; m.blogname) <br/> @Html. textboxfor (M => m.blogname, new {maxlength =}) @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= "submitted" /> </li> </ul> </fieldset> </form>

 

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

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

(3) Obtain the file name according to the path of the upload:

 function Getnamefrompath (strFilePath) {
  var objre = new RegExp (/([^\/\\]+) $/);
  var strName = objre.exec (strFilePath);

  if (StrName = = null) {return
   null;
  }
  else {return
   strname[0];
  }
 }

(4) When changing the file, trigger the Change event 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 extension jpg,png,gif,pdf!") ");
    return false;
   }
   else {
    var size = GetFileSize (' Blogphoto ');
    if (Size > 4) {
     Filesizebool = true;
     $ ("#warning"). html ("Upload file has more than 4 megabytes!"). ");
    } else {
     Filesizebool = false;}}}
  ;

(5) When the Submit button is clicked to verify its file:

  $ ("#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 is not too complete for verification, but the basic shelves have been given.

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

We have been using the pure HTML code, of course, can also use the expansion of MVC method to do, as follows (the final rendering or form, is essentially consistent, 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=
 "commit"/>
}

Conclusion
in this section we describe in more detail how to upload files in MVC, but one thing we have not yet mentioned is to insert the data into the database using the stream to convert the images as we described above into bytes.

Refer to this article for upload. NET to this use stream to upload.

Author and original text connection: Recluse_xpy http://www.cnblogs.com/CreateMyself/p/5414200.html

The above is the entire content of this article, I hope to help you learn.

Related Article

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.