ASP. net mvc File Upload tutorial (1), asp. netmvc

Source: Internet
Author: User

ASP. net mvc File Upload tutorial (1), asp. netmvc

This section describes how to upload files in MVC. Let's take a closer look.

Upload File (1)
Add the following to the Home controller in the default project:

  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 to the UploadFile View:

<Form action = "/Home/UploadFile" method = "post" enctype = "multipart/form-data"> <input type = "file" name = "file"/> <br/> <input type = "submit" value = "submit"/> </form>

We don't have to say much about the view. We only need to understand the following two points:

(1) HttpPostedFileBase is used in the background to receive uploaded files. This class is an abstract class, but this class is not available in ASP. NET Web Form. This class is used for better unit testing.

(2) In the view, the file type name must be consistent with the parameter of the file received in the background.

Next, let's demonstrate the results:

In the above process, we simply uploaded an Excel file. In the following example, we use a strong view and model verification to enhance the upload process.

Upload File (2)
We create the following BlogModel class:

Public class BlogModel {[Display (Name = "blog Name")] [Required (ErrorMessage = "Enter your blog Name! ")] Public string BlogName {get; set;} [Display (Name =" blog address ")] [Required (ErrorMessage =" 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 ;}}

The features of the above files are not verified. You can only customize the file features 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 = "upload your blog image type:" + string. join (",", AllowedFileExtensions); return false;} else if (file. contentLength> MaxContentLength) {ErrorMessage = "The uploaded image is too large and cannot exceed 4 MB:" + (MaxContentLength/1024 ). toString () + "MB"; return false;} else return true ;}}

We can set the size of the uploaded file to 40 MB. In the configuration file, we know that maxRequestLength = 4096 is 4 MB by default. Of course, we can change the default setting.

<HttpRuntime targetFramework = "4.5" executionTimeout = "1100" maxRequestLength = "40960"/>
In this case, 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 take a look at the effect:

What's going on? It seems that our file is too large. After reading this file, there are close to 45 MB, But we set it to 40 MB, as a result, the file size is modified in the configuration file, but the result is the same. Let's continue to take a closer look at the prompts of this result. Find the node in the configuration file as prompted and try again. We set it to 2G under the syste. webServer node:

 <security>  <requestFiltering>  <requestLimits maxAllowedContentLength="2147483647">  </requestLimits>  </requestFiltering> </security>

The results are good. I checked and found someone who encountered similar problems. It seems that I only gave a result, but I didn't explain it. Why can't I set it in httpRuntime, but some of these settings are correct. Why? Finally, I found the answer:

(1) In IIS 5 and IIS 6, the maximum size of files to be uploaded is 4 MB by default. When the size of the uploaded files exceeds 4 MB, an error message is displayed, however, we can set the file size as shown in the following figure.

<system.web> 

(2) In IIS 7, the maximum size of the default file to be uploaded is 28.6 mb. When the default size is exceeded, an error message is returned, however, you can set the file upload size.

<system.webServer> <security> <requestFiltering>  <requestLimits maxAllowedContentLength="2147483647" /> </requestFiltering> </security></system.webServer>

[Likewise, I think it may be that IIS 7 + or above sets the file upload size through IIS 7 above]

Although we verify the image on the server side, we still feel that this is not safe. We continue to verify the image type and size uploaded on the client side.

(1) Use a strong 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 {maxlength = 50}) @ Html. validationMessageFor (m => m. blogName) </li> <li> @ Html. labelFor (m => m. blogAddress) <br/> @ Html. textBoxFor (m => m. blogAddress, new {maxlength = 200}) @ 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> <input type =" submit "value =" submit "/> </li> </ul> </fieldset> </form>

(2) Use a script to get the size of the uploaded file:

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

(3) obtain the file name based on the upload 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 the file type and 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" pai.html ( "Only jpg, png, gif, and pdf files can be uploaded! "); Return false;} else {var size = GetFileSize ('blogphoto '); if (size> 4) {fileSizeBool = true; $ ("# warning" pai.html ("the uploaded file has exceeded 4 MB! ") ;}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 verification is not complete, but the basic shelf has been given.

Next we will give a complete demonstration of the entire process.

The above is the pure HTML code we have been using. Of course, the MVC extension method can also be used as follows (the final rendering or form is essentially consistent, so we will not discuss it too much)

@ 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
This section describes in detail how to upload files in MVC, but we have not mentioned any more, it is to use the stream to convert the above image into bytes and insert it into the database.

For upload, refer to this Article. NET to use stream for upload.

Recluse_Xpy http://www.cnblogs.com/CreateMyself/p/5414200.html

The above is all the content of this article, hoping 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.