ASP. net mvc File Upload tutorial (2). mvc File Upload

Source: Internet
Author: User

ASP. net mvc File Upload tutorial (2). mvc File Upload

ASP. net mvc File Upload tutorial (1) We talked about simple uploads and precautions. When checking relevant information, I feel that there are still a lot of content involved in the upload, therefore, we will divide the upload part into several sections for processing. At the same time, we will also talk about the omissions in C # during upload, so we can check for missing content in time, try to perfect this piece.

Introduction
In the previous section, we talked about uploading this part. Some friends suggested that uploading large files is not involved. They tried to do this before thinking about it. After all, they didn't think about this issue carefully, in particular, we can also contact a series of questions such as creating folders in actual development. At the same time, we need to create another wheel for users to search for a large number of components on the Internet, what I need to do is to review and further explore the basics and find some detailed problems and solve them.

Deep upload
I declare again that we will not discuss too much about the upload progress. If such a component is available, we can find it on our own. We only need to implement the core one.

We can imagine the same scenario: In the blog garden, every blogger can upload files, scripts, and so on. We can use the name of the garden friends to create files uploaded by every garden friend, next we will implement this scenario.

Since the file is created for the corresponding blog name, it is a class such as the corresponding blog. As follows:

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

  public string Id { get; set; }
 }

You can create a folder by using the blog name and create a sub-folder with a unique Id under the folder. The uploaded files are stored in the attachment (atttachment) under the Id folder. Next we need to sort out the entire file upload process. Is this obviously not the best way to directly upload the file to the corresponding folder, when the upload is interrupted, the file created in the folder is not complete, but it is a junk file. Instead, we create a temporary file first, even if the upload fails, we can regularly clean up temporary files, that is, junk files. If the upload is not interrupted, we will move the temporary files to our corresponding folder when the upload is complete. We can see that this is also true when downloading files. Next, let's start implementation.

(1) We provide a static UploadManager class for upload. We can write the name of the uploaded folder or customize the name of the uploaded folder through the configuration file.

static UploadManager()
{
//Get upload folder from profile
if (String.IsNullOrWhiteSpace(WebConfigurationManager.AppSettings["UploadFolder"]))
UploadFolderRelativePath = @"~/upload";
Else
UploadFolderRelativePath = WebConfigurationManager.AppSettings["UploadFolder"];
UploadFolderPhysicalPath = HostingEnvironment.MapPath(UploadFolderRelativePath);
if (!Directory.Exists(UploadFolderPhysicalPath))
Directory.CreateDirectory(UploadFolderPhysicalPath);
}

The above indicates that you can customize the upload folder in the configuration file (giving the upload Virtual Path), for example:

<! -- <Add key = "UploadFolder" value = "~ /UploadFile/"> -->

(2) core methods for saving files

[SuppressMessage("Microsoft.Usage", "CA2202:Do not dispose objects multiple times")]
public static bool SaveFile(Stream 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 if the subfolder of the upload folder does not exist
var file = new FileInfo(targetPath);
if (file.Directory != null &amp;&amp; !file.Directory.Exists)
file.Directory.Create();
using (FileStream fs = File.Open(tempPath, FileMode.Append))
{
if (stream.Length > 0)
{
SaveFile(stream, fs);
}
Fs.Close ();
}
//After uploading, move the temporary file to the target file
File.Move(tempPath, targetPath);
}
}
catch (Exception)
{
//If the upload error occurs, delete the file uploaded to the folder
if (File.Exists(targetPath))
File.Delete(targetPath);
//Delete temporary files
if (File.Exists(tempPath))
File.Delete(tempPath);
return false;
}
Finally
{
//Delete temporary files
if (File.Exists(tempPath))
File.Delete(tempPath);
}
Return true;
}

(3) cyclically read data to the 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 and call 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, let's test the effect by uploading a 84M file (wait a moment, the file is a bit large ).


Sorry, I was disappointed. It is different from yesterday's error. Today's error is: exceeding the maximum request length. Next, let's take a look at what we said yesterday. My IIS is 10.0, that is, on IIS 7 +. It should be okay to set it as yesterday. Is it related to another setting, let's look at the configuration in the configuration file.

<HttpRuntime targetFramework = "4.5"/>
If this parameter is not set yet, will it go wrong if it exceeds the default value of 28.6M? Let's set it to 2 GB.

<HttpRuntime targetFramework = "4.5" executionTimeout = "1100" maxRequestLength = "2147483647"/>


Okay. The above error is not displayed even if the upload is successful.

Conclusion
This section describes how to use stream to process large files, but there is still a small problem. We will make a summary together with yesterday:

(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>
<httpRuntime maxRequestLength="2147483647" executionTimeout="100000" />
</system.web>
(2) In IIS 7 +, the maximum upload size of the default file is 28.6 megabytes. When the default file size is exceeded, an error message will also be obtained. However, we can set the upload size of the file through the following steps (also set the above settings).
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="2147483647" />
</requestFiltering>
</security>
</system.webServer>
On how to set the file size without error in the configuration file, I have finally made a final summary, and I will continue to fight.
Author: recluse_xpy
Link to this article: http://www.cnblogs.com/createmyself/p/5419594.html
The above is about asp.net MVC file upload all content introduction, hope to help everyone's learning.

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.