asp.net mvc file Upload Tutorial (ii) _ Practical skills

Source: Internet
Author: User
Tags file upload static class unique id

Above asp.net MVC file Upload Tutorial (a) We talked about the simple upload and need to pay attention to the place, check the relevant information, feel the upload involved in the content or more, so will upload this piece divided into several sections to deal with, and follow-up will also talk about doing upload when the missing C # should pay attention to the place, In time to check the leak fill, as far as possible to improve this piece.

Introduced
In the last section we talked about uploading this piece, a friend proposed not involved in large file upload this piece, after thought or to try to do, after all, not how to carefully consider this issue, in particular, you can create a series of problems with the development of the Internet, as well as the upload of a random look at the online are full of a large number of components, Why do we have to build wheels, what I need to do is just to review the basics and further in-depth and in the process of doing the discovery of some of the details of the problem and solve the enough, do not like to spray.

Deep upload
again, the upload can show the upload progress and so we do not do too much discussion, there are such components, on their own to find, we need to achieve the core of this piece can be compared.

We can imagine the same scenario: for example, in a blog park, each blogger can upload files such as pictures, scripts, and so on, we can use the name of the garden friends to create each of the files uploaded by the friends, then we realize such a scene.

Since it is the name of the corresponding blog to create a file, that is, the corresponding blog needs a class. As follows:

 public class Blogsample
 {public
  string UserName {get; set;}

  public string Id {get; set;}
 }

We create a subfolder with the name of the blog and create it under that folder with a unique ID, which stores the uploaded file in the attachment (atttachment) under the ID folder. Next we need to comb through the entire upload file process. Do you want to upload the file directly to upload to the corresponding folder, this is obviously not optimal, when there is an upload interrupt, the file created in the folder is not complete is a spam file, and we directly create a temporary file, even if the upload failed we can periodically clean up the temporary file is the garbage file, if not interrupted, The temporary files are moved to our corresponding folder when the upload is complete. It is obvious that we are doing this when we actually download the file. Next we start to implement.

(1) We give a UploadManager static class about the upload, we can write dead uploaded folder name or custom upload folder name through the configuration file.

  Static UploadManager ()
  {
   //Gets the upload folder from the configuration file
   if (String.isnullorwhitespace ( webconfigurationmanager.appsettings["Uploadfolder"])
    Uploadfolderrelativepath = @ "~/upload";
   else
    Uploadfolderrelativepath = webconfigurationmanager.appsettings["Uploadfolder"];

   Uploadfolderphysicalpath = Hostingenvironment.mappath (Uploadfolderrelativepath);

   if (! Directory.Exists (Uploadfolderphysicalpath))
    directory.createdirectory (Uploadfolderphysicalpath);
  }

As indicated above, you can customize the upload folder in the configuration file (give the upload virtual path), for example:

<!--<add key= "Uploadfolder" value= "~/uploadfile/" >-->

(2) The core method of saving files

  [SuppressMessage (' Microsoft.Usage ', ' Ca2202:do not dispose objects multiple times ')] public static bool SaveFile (stre Am Stream, String fileName, String userName, String guid) {string TempPath = string. Empty, TargetPath = string.

   Empty;

    try {string tempfilename = Gettempfilepath (fileName);
     if (userName!= null) {var contentType = UserName;

     var ContentID = GUID;
     TempPath = Gettempfilepath (tempfilename); TargetPath = Gettargetfilepath (FileName, ContentType, ContentID, String.


     Empty, Filessubdir);
     Create var file = new FileInfo (TargetPath) If the upload folder does not exist in the neutron folder; if (file. Directory!= null &&!file. directory.exists) file.

     Directory.create (); using (FileStream fs = File.Open (TempPath, filemode.append)) {if (stream).
      Length > 0) {savefile (stream, FS); } fs.
     Close ();
    ///upload the temporary files to the target file File.move (TempPath, TargetPath); } catch (Exception) {//If the upload error, then delete uploaded to the folder file if (file.exists (TargetPath)) File.delete (TargetPath);

    Delete temporary file if (file.exists (TempPath)) File.delete (TempPath);
   return false;
   Finally {//delete temporary file if (file.exists (TempPath)) File.delete (TempPath);
  return true;

 }

(3) loop read stream to file stream

   <summary>
  ///Loop read stream to file stream
  ///</summary>
  ///<param name= "Stream" ></param>
  ///<param name= "FS" ></param> public
  static void SaveFile (Stream stream, FileStream fs)
  {
   var buffer = new byte[4096];
   int bytesread;
   while (bytesread = stream. Read (buffer, 0, buffer.) Length))!= 0)
   {
    fs. Write (buffer, 0, bytesread);
   }
  

(4) Start writing test data to invoke the method:

   var testsample = new Blogsample () {UserName = "xpy0928", Id = Guid.NewGuid (). ToString ("N")};
   if (modelstate.isvalid)
   {
    var fileName = bModel.BlogPhoto.FileName;
    var success = Uploadmanager.savefile (BModel.BlogPhoto.InputStream, FileName, Testsample.username, testsample.id);
    if (!success)
    {
     //TODO (your code)
    }
    //var FilePath = Server.MapPath (string. Format ("~/{0}", "File"));
    BModel.BlogPhoto.SaveAs (Path.Combine (FilePath, FileName));
    Modelstate.clear ();
   }

Next, we'll test it by uploading a 84M file to see the effect (Wait a minute, the file is a bit large).

Sorry, I was disappointed, and yesterday's error is not the same, today's error is: exceed the maximum request length. Let's take a look at yesterday and say, my IIS is 10.0, that is, on IIS 7+, the setup should be OK with yesterday, is it related to another setting, let's look at the configuration in the configuration file.


Not set, more than the default setting of 28.6M error, we set the 2G to see.


Good, upload success also did not appear above error.

Conclusion
in this section we talked about using the stream to do large file processing, but there is still a little problem, and yesterday together to do a summary:

(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 will get error message, but we can set the file upload size (also to be set as above).

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

about how to set the file size in the configuration file without error, finally make a final summary, have the harvest, continue to fighting.
Article author: recluse_xpy
This article links: http://www.cnblogs.com/CreateMyself/p/5419594.html
The above is about asp.net MVC file upload all content introduction , 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.