Set of methods for uploading and downloading files in ASP. NET (upload restriction, storage method-binary or file format, uploading Internet resources)

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, we can change the Web. the Config file defines the maximum file size as follows:

In this way, the maximum size of the uploaded file is 4 MB, but this does not allow us to infinitely expand the value of MaxRequestLength, because ASP. NET will load all the files into the memory and then process them. The solution is to use the implicit HttpWorkerRequest and its GetPreloadedEntityBody and ReadEntityBody methods to read data from the pipe created by IIS for ASP. NET in blocks. 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. 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 An ASPX page and then retrieve the binary byte stream in its page_load () event, then you can read it again. In fact, this method is not advisable. In actual use, there may be errors that cannot open a site. I generally use the following method:

First, add the following content to Web. config:

<Add verb = "*" Path = "openfile. aspx" type = "ruixinoa. Web. baseclass. openfile, ruixinoa. Web"/>
This means that when I open the openfile. ASPX page, the system will automatically go to the method in the ruixinoa. Web. baseclass. openfile class. 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.

This article from the CSDN blog, reproduced please indicate the source: http://blog.csdn.net/lee576/archive/2009/03/05/3959273.aspx

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.