In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly introduces ASP.NET MVC how to achieve file upload, the article is very detailed, has a certain reference value, interested friends must read it!
Upload File (1)
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 to the UploadFile view:
There is no need to say much about the view, just to understand the following two points:
(1) use HttpPostedFileBase to receive uploaded files in the background. This class is an abstract class, but there is no such class in ASP.NET Web Form. This kind of class appears for better unit testing.
(2) the name of the file type in the view should be consistent with the parameters of the receiving file in the background.
Next, let's demonstrate the results:
We simply uploaded an Excel file above, and now we enhance the upload through strongly typed views and model verification.
Upload File (2)
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 picture")] [Required (ErrorMessage = "Please upload your blog picture!")] [ValidateFile] public HttpPostedFileBase BlogPhoto {get; set;}}
The above properties of the file are not verified. You can only customize the file properties 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 image type:" + string.Join (",", AllowedFileExtensions); return false;} else if (file.ContentLength > MaxContentLength) {ErrorMessage = "upload image is too large to exceed 4 megabytes:" + (MaxContentLength / 1024). ToString () + "MB"; return false } else return true;}}
We can set the size of the uploaded file at will. We set it to 40 megabytes. In the configuration file, we know that maxRequestLength = 4096 defaults to 4 megabytes. Of course, we can change its default setting.
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 take a look at the effect:
What's the matter? when something goes wrong, it seems that our file is too large. We took a look at the file with nearly 45 megabytes, but we set it to 40 megabytes, so we continued to modify the file size in the configuration file, but the result was the same. Let's continue to take a closer look at the hint of the result, follow the prompt to find the node under the configuration file and try again, we set it to 2G under the syste.webServer node:
The result worked well. After checking, there are people who have encountered similar problems. It seems that they can only give a result, but they do not explain why it is not possible to set it up in httpRuntime, but some of these settings are correct. What is the reason? Finally found the answer:
(1) in IIS 5 and IIS 6, the default maximum file upload size is 4 megabytes. When the uploaded file size exceeds 4 megabytes, you will get an error message, but we set the file size as shown below.
(2) in IIS 7, the maximum default file upload is 28.6 megabytes. When the default file upload size is exceeded, you will also get an error message, but we can set the file upload size as below.
[by analogy, I think it is possible that the file upload size is set above IIS 7 + through IIS 7 above]
Although we verify it on the server side, we don't think it is safe, and we continue to verify the type and size of the images uploaded on the client side.
(1) the view code is given by using strongly typed view:
Field-validation-error {color: red } @ Html.LabelFor (m = > m.BlogName) @ Html.TextBoxFor (m = > m.BlogName, new {maxlength = 50}) @ Html.ValidationMessageFor (m = > m.BlogName) @ Html.LabelFor (m = > m.BlogAddress) @ Html.TextBoxFor (m = > m.BlogAddress, new {maxlength = 200}) @ Html.ValidationMessageFor (m = > m.BlogAddress) @ Html.LabelFor (m = > m.BlogPhoto) @ Html.TextBoxFor (m = > m.BlogPhoto) New {type = "file"}) @ Html.ValidationMessageFor (m = > m.BlogPhoto)
(2) use script to obtain the uploaded 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 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 ("uploaded files have exceeded 4 megabytes!") ;} else {fileSizeBool = false;}})
(5) verify the document 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 is not complete for verification, but the basic shelf has been given.
Let's demonstrate the whole process in its entirety.
We have been using the pure HTML code mentioned above, of course, we can also use the extension method of MVC, as follows (the final rendering is still the form, which is essentially consistent, so we won't discuss it too much)
@ using (Html.BeginForm ("UploadFile", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}) {} above is all the content of the article "how to upload files by ASP.NET MVC". Thank you for reading! Hope to share the content to help you, more related knowledge, welcome to follow the industry information channel!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.