Asp.net large attachment upload Problems

Source: Internet
Author: User
File Upload/download is a technology that we often use in the actual project development process. Several common methods are provided here. The main content of this article includes:

1. How to Solve the file upload size limit

2. Save the file to the server

3. convert to a binary byte stream, save it to the database, and download it

4. Upload Internet Resources

Part 1:

First, let's talk about how to solve the file upload size limit in ASP.net. We know ASP by default.. NET file upload size is limited to 2 MB. In general, you can change the web. config and
The machine. config file configures the website and website directories. The web. config file contains some special configuration information required by a specific application, such as session Status settings.
And Authentication Settings. The machine. config file contains the configuration information of the entire server. web. config can be saved or rewritten from machine. config.
Some configuration information. You can configure two parts for a specific website. One is the machine. config configuration for the entire server, and the other is for the hope site.
The web. config configuration. web. config file is usually stored in the root directory of the website. Its configuration information takes effect for the Directory and sub-directories in the directory.
(1) modify the web. config file
Add the


<Configuration>
<System. web>
<HttpRuntime maxRequestLength = "4096" // this size is the default value and can be modified as needed
ExecutionTimeout = "600" // This value specifies that the file upload is valid for 10 minutes.

/>

</System. web>

</Configuration>

(2) modify the machine. config file
In"
% \ Microsoft. NET \ Framework \ v1.0.3705 \ config "(version 1.0> or" % \ Microsoft. NET \
Framework \ v1.1.4322 \ config "(Version 1.1> machine. config file. You can open the machine. config file.
The following code is displayed:
<! --
HttpRuntime Attributes:
ExecutionTimeout = "[seconds]"-time in seconds before request is automatically timed out
MaxRequestLength = "[KBytes]"-KBytes size of maximum request length to accept
UseFullyQualifedREdirectUrl = "[true | false]"-fully qualifiy the URL for client redirects
MinFreeThreads = "[count]"-minmum number of free thread to allow execution of new requests
MinLocalRequestFreeThreads = "[count]"-minmum number of free thread to allow execution of new local requests
AppRequestQueueLimit = "[count]"-maxmum number of Requests queued for the application -->
<HttpRuntime executionTimeout = "90" maxRequestLength = "4096" useFullyQualifiedRedirectUrl = "false" minFreeThreads = "8"
MinLocalRequestFreeThreas = "4" appRequestQueueLimit = "100"/>
In the code above, the executionTimeout attribute is used to specify the effective time (in seconds) for the upload operation ). the maxRequestLength attribute is used to specify the maximum number of bytes of the uploaded file, in KB. The default size of this attribute is 4096 K (4 MB ). you can modify this attribute to set the size of the uploaded file.

   This
The maximum size of the uploaded file is 4 MB, but this does not allow us to expand infinitely.
The value of MaxRequestLength, because ASP. NET loads all files into the memory before processing. The solution is to use implicit
HttpWorkerRequest, using its GetPreloadedEntityBody and ReadEntityBody methods from IIS to ASP. NET
Blocks The created pipe to read data. The implementation method is as follows: IServiceProvidERProvider = (IServiceProvider) HttpContext. Current;
HttpWorkerRequestwr = (HttpWorkerRequest) provider. GetService (typeof (HttpWorkerRequest ));
Byte [] bs = wr. GetPreloadedEntityBody ();
.
If (! Wr. IsEntireEntityBodyIsPreloaded ())
{
Intn = 1024;
Byte [] bs2 = newbyte [n];
While (wr. ReadEntityBody (bs2, n)> 0)
{
..
}
}

This solves the problem of uploading large files.

Part 2:

Next we will introduce how to upload a client file to the server as a file and return some basic information about the uploaded file.

First, we define a class to store the information of the uploaded file (required when returned ). Public class FileUpLoad
{
Public FileUpLoad ()
{}
/**////

/// Upload File Name
///

Public string FileName
{
Get
{
Return fileName;
}
Set
{
FileName = value;
}
}
Private string fileName;

/**////

/// Upload File Path
///

Public string FilePath
{
Get
{
Return filepath;
}
Set
{
Filepath = value;
}
}
Private string filepath;

/**////

/// File Extension
///

Public string FileExtension
{
Get
{
Return fileExtension;
}
Set
{
FileExtension = value;
}
}
Private string fileExtension;
}

In addition, you can restrict the format of the uploaded file (App. Config) in the configuration file: <? XML version = "1.0" encoding = "gb2312"?>
<Application>
<FileUpLoad>
<Format>. jpg |. gif |. png |. bmp
</FileUpLoad>
</Application>

In this way, we can start writing our file upload method, as follows: public FileUpLoad UpLoadFile (HtmlInputFile InputFile, string filePath, string myfileName, bool isRandom)
{
FileUpLoad fp = new FileUpLoad ();
String fileName, fileExtension;
String saveName;

//
// Create an upload object
//
HttpPostedFile postedFile = InputFile. PostedFile;

FileName = System. IO. Path. GetFileName (postedFile. FileName );
FileExtension = System. IO. Path. GetExtension (fileName );

//
// Determine the file format based on the Type
//
AppConfig app = new AppConfig ();
String format = app. GetPath ("FileUpLoad/Format ");

//
// Return if none of the formats are correct
//
If (format. IndexOf (fileExtension) =-1)
{
Throw new ApplicationException ("the format of uploaded data is invalid ");
}

//
// Generate a random file name based on the date and random number.
//
If (myfileName! = String. Empty)
{
FileName = myfileName;
}

If (isRandom)
{
Random objRand = new Random ();
System. DateTime date = DateTime. Now;
// Generate random file names
 
SaveName = date. Year. ToString () + date. Month. ToString () +
Date. Day. ToString () + date. Hour. ToString () + date. Minute. ToString () +
Date. Second. ToString () + Convert. ToString (objRand. Next (99) * 97 + 100 );
FileName = saveName + fileExtension;
}

String phyPath = HttpContext. Current. Request. MapPath (filePath );

// Determine whether a path exists. If not, create a path.
DirectoryInfo upDir = new DirectoryInfo (phyPath );
If (! UpDir. Exists)
{
UpDir. Create ();
}

//
// Save the file
//
Try
{
PostedFile. SaveAs (phyPath + fileName );

Fp. FilePath = filePath + fileName;
Fp. FileExtension = fileExtension;
Fp. FileName = fileName;
}
Catch
{
Throw new ApplicationException ("Upload Failed! ");
}

// Return the information of the uploaded object
Return fp;
}

Then we can call this method when uploading files, and save the returned file information to the database. As for downloading, it is OK to open the path directly.

Part 3:

Here we will mainly talk about how to upload and download files in binary format. First, the upload method is as follows: public byte [] UpLoadFile (HtmlInputFile f_IFile)
{
// Obtain access to the uploaded file specified by the client
HttpPostedFile upFile = f_IFile.PostedFile;
// Get the length of the uploaded file
Int upFileLength = upFile. ContentLength;
// Obtain the client MIME type of the uploaded file
String contentType = upFile. ContentType;
Byte [] FileArray = new Byte [upFileLength];

Stream fileStream = upFile. InputStream;

FileStream. Read (FileArray, 0, upFileLength );
Return FileArray;
}

 
This method returns the binary byte stream of the uploaded file, so that we can save it to the database. Next let's talk about this form of download. You may think that this method of download is to create
Aspx page, and then extract the binary byte stream in its Page_Load () event, and then read it out. In fact, this method is not desirable, in practical use, it may fail.
An error occurs when a website is opened. I generally use the following method:

First, add <add verb = "*" path = "openfile. aspx" type = "RuixinOA. Web. BaseClass. OpenFile, RuixinOA. Web"/> to Web. config.

This means that when I open the openfile. aspx page, the System will automatically go to the method in the class RuixinOA. Web. BaseClass. OpenFile. The specific implementation is as follows: using System;
Using System. Data;
Using System. Web;
Using System. IO;
Using Ruixin. WorkFlowDB;
Using RXSuite. Base;
Using RXSuite. Component;
Using RuixinOA. BusinessFacade;

Namespace RuixinOA. Web. BaseClass
{
/**////

/// Summary of NetUFile.
///

Public class OpenFile: IHttpHandler
{
Public void ProcessRequest (HttpContext context)
{
// Retrieve the file information to be downloaded from the database
RuixinOA. BusinessFacade. RX_OA_FileManager OS = new RX_OA_FileManager ();
EntityData data = OS. GetFileDetail (id );

If (data! = Null & data. Tables ["RX_OA_File"]. Rows. Count> 0)
{
DataRow dr = (DataRow) data. Tables ["RX_OA_File"]. Rows [0];
Context. Response. Buffer = true;
Context. Response. Clear ();
Context. Response. ContentType = dr ["CContentType"]. ToString ();
Context. Response. AddHeader ("Content-Disposition", "attachment; filename =" + HttpUtility. UrlEncode (dr ["CTitle"]. ToString ()));
Context. Response. BinaryWrite (Byte []) dr ["CContent"]);
Context. Response. Flush ();
Context. Response. End ();
}
}
Public bool IsReusable
{
Get {return true ;}
}
}
}

After the above method is executed, the system will prompt you to choose whether to open or download directly. Let's talk about this part.

Part 4:

This section mainly describes how to upload an Internet resource to the server.

First, you need to reference the namespace System. Net, and then perform the following operations: HttpWebRequest hwq = (HttpWebRequest) WebRequest. Create ("http: // localhost/pwtest/webform1.aspx ");
HttpWebResponse hwr = (HttpWebResponse) hwq. GetResponse ();
Byte [] bytes = new byte [hwr. ContentLength];
Stream stream = hwr. GetResponseStream ();
Stream. Read (bytes, 0, Convert. ToInt32 (hwr. ContentLength ));
// HttpContext. Current. Response. BinaryWrite (bytes );

HttpWebRequest can read files from the Internet, so this problem can be well solved.

Part 5: Summary

Today, I briefly introduced several methods for uploading and downloading files, which are frequently used in actual project development and may be imperfect, I hope you can share your experiences in project development with each other.

In this project, a large file upload is used, and the number of files to be uploaded is more than 100 MB.
Components are found to use two controls: AspnetUpload 2.0 and Lion. Web. UpLoadModule. In addition, you can also think about the methods described in its blog. Examples and
The ReadEntityBody method reads data from the pipe created by IIS for ASP. NET in blocks. Chris Hynes provides us with such a solution (using HttpModule) that allows you to upload large files and display the upload progress in real time.
Lion. Web. UpLoadModule and AspnetUpload both use this solution.
When the leaflet file is used, the two software methods are the same, inheriting the HttpModule
HttpApplication application1 = sender as HttpApplication;
HttpWorkerRequest request1 = (HttpWorkerRequest)
(IServiceProvider)
HttpContext. Current). GetService (typeof (HttpWorkerRequest ));
Try
{
If (application1.Context. Request. ContentType. IndexOf ("multipart/form-data") <=-1)
{
Return;
}
// Check The HasEntityBody
If (! Request1.HasEntityBody ())
{
Return;
}

Int num1 = 0;
TimeSpan span1 = DateTime. Now. Subtract (this. beginTime );

String text1 = application1.Context. Request. ContentType. ToLower ();

Byte [] buffer1 = Encoding. ASCII. GetBytes ("\ r \ n --" +
Text1.Substring (text1.IndexOf ("boundary =") + 9). ToCharArray ());

Int num2 = Convert. ToInt32 (request1.GetKnownRequestHeader (11 ));
Progress progress1 = new Progress ();

Application1.Context. Items. Add ("FileList", new Hashtable ());

Byte [] buffer2 = request1.GetPreloadedEntityBody ();
Num1 + = buffer2.Length;

String text2 = this. AnalysePreloadedEntityBody (buffer2, "UploadGUID ");
If (text2! = String. Empty)
{
Application1.Context. Items. Add ("LionSky_UpLoadModule_UploadGUID", text2 );
}
Bool flag1 = true;
If (num2> this. UpLoadFileLength () & (0
> Span1.TotalHours) | (span1.TotalHours> 3 )))
{
Flag1 = false;
}
If (0> span1.TotalHours) | (span1.TotalHours> 3 ))
{
Flag1 = false;
}
String text3 = this. AnalysePreloadedEntityBody (buffer2, "UploadFolder ");
ArrayList list1 = new ArrayList ();
RequestStream stream1 = new RequestStream (buffer2, buffer1,
Null, RequestStream. FileStatus. Close,
RequestStream. ReadStatus. NoRead, text3, flag1,
Application1.Context, string. Empty );
List1.AddRange (stream1.ReadBody );
If (text2! = String. Empty)
{
Progress1.FileLength = num2;
Progress1.ededlength = num1;
Progress1.FileName = stream1.OriginalFileName;
Progress1.FileCount = (Hashtable) application1.Context. Items ["FileList"]). Count;
Application1.Application ["_ UploadGUID _" + text2] = progress1;
}
If (! Request1.IsEntireEntityBodyIsPreloaded ())
{
Byte [] buffer4;
ArrayList list2;
Int Number3 = 204800;
Byte [] buffer3 = new byte [num3];
While (num2-num1)> = num3)
{
If (! Application1.Context. Response. IsClientConnected)
{
This. ClearApplication (application1 );
}
Num3 = request1.ReadEntityBody (buffer3, buffer3.Length );
Num1 + = num3;
List2 = stream1.ContentBody;
If (list2.Count> 0)
{
Buffer4 = new byte [list2.Count + buffer3.Length];
List2.CopyTo (buffer4, 0 );
Buffer3.CopyTo (buffer4, list2.Count );
Stream1 = new RequestStream (buffer4, buffer1,
Stream1.FileStream, stream1.FStatus, stream1.RStatus, text3,
Flag1, application1.Context, stream1.OriginalFileName );
}
Else
{
Stream1 = new RequestStream (buffer3, buffer1,
Stream1.FileStream, stream1.FStatus, stream1.RStatus, text3,
Flag1, application1.Context, stream1.OriginalFileName );
}
List1.AddRange (stream1.ReadBody );
If (text2! = String. Empty)
{
Progress1.ededlength = num1;
Progress1.FileName = stream1.OriginalFileName;
Progress1.FileCount = (Hashtable) application1.Context. Items ["FileList"]). Count;
Application1.Application ["_ UploadGUID _" + text2] = progress1;
}
}
Buffer3 = new byte [num2-num1];
If (! Application1.Context. Response. IsClientConnected &&
(Stream1.FStatus = RequestStream. FileStatus. Open ))
{
This. ClearApplication (application1 );
}
Num3 = request1.ReadEntityBody (buffer3, buffer3.Length );
List2 = stream1.ContentBody;
If (list2.Count> 0)
{
Buffer4 = new byte [list2.Count + buffer3.Length];
List2.CopyTo (buffer4, 0 );
Buffer3.CopyTo (buffer4, list2.Count );
Stream1 = new RequestStream (buffer4, buffer1,
Stream1.FileStream, stream1.FStatus, stream1.RStatus, text3,
Flag1, application1.Context, stream1.OriginalFileName );
}
Else
{
Stream1 = new RequestStream (buffer3, buffer1,
Stream1.FileStream, stream1.FStatus, stream1.RStatus, text3,
Flag1, application1.Context, stream1.OriginalFileName );
}
List1.AddRange (stream1.ReadBody );
If (text2! = String. Empty)
{
Progress1.ReceivedLength = num1 + buffer3.Length;
Progress1.FileName = stream1.OriginalFileName;
Progress1.FileCount = (Hashtable) application1.Context. Items ["FileList"]). Count;
If (flag1)
{
Progress1.UploadStatus = Progress. UploadStatusEnum. Uploaded;
}
Else
{
Application1.Application. Remove ("_ UploadGUID _" + text2 );
}
}
}
Byte [] buffer5 = new byte [list1.Count];
List1.CopyTo (buffer5 );
This. PopulateRequestData (request1, buffer5 );
}
Catch (Exception exception1)
{
This. ClearApplication (application1 );
Throw exception1;
}

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.