Set of methods for uploading and downloading files in ASP. NET (For details, refer)
[O] consider the following before we describe the method:
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
I. File size restrictions
First, let's talk about how to solve ASP. net file upload size restrictions, we know that by default ASP.. 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:
<Httpruntime executiontimeout = "300" maxrequestlength = "40960" usefullyqualifiedredirecturl = "false"/> in this way, the maximum value of the uploaded file is 4 MB, however, this does not allow us to infinitely expand the value of maxrequestlength, because ASP. net loads all files into the memory and then processes 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,
Ii. Save the uploaded files directly to the server
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 () {} /** // <Summary> /// Upload File Name /// </Summary> Public String filename { Get { Return filename; } Set { Filename = value; } } Private string filename;/** // <Summary> /// Upload File Path /// </Summary> Public String filepath { Get { Return filepath; } Set { Filepath = value; } } Private string filepath; /** // <Summary> /// File Extension /// </Summary> 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 </format> </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.
3. upload and download files in binary format
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 {< br>/** /// /// Summary of netufile. // public class openfile: ihttphandler {< br> Public void processrequest (httpcontext context) {< br> // retrieve information about the file 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.
4. upload an Internet resource to the server
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.