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 ):
Set of methods for uploading and downloading files in ASP. NET Source: network collection | Author: Unknown | browse:
83 | send to friends | add to favorites
2 pages in total, 2nd pages 1 2 previous pages
<? 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.
| Asp.net large attachment upload Problems |
| Source: |
Author: |
Release date: 2006-10-18 |
| |
The rfc1867 standard can be used to process files: 1. Get the uploaded data at one time and analyze and process it. After reading n multiple codes, I found that currently no component program and some COM components use the request. binaryread method. Obtain the uploaded data at a time, and then analyze and process it. This is why the upload of large files is slow. If IIS times out, even if hundreds of MB of files are uploaded, the analysis takes a while. 2. Write to the hard disk while receiving files. I have learned about commercial components outside China. Some popular components include power-web, aspupload, activefile, abcupload, aspsmartupload, and Sa-fileup. Among them, the better is aspupload and SA-FILE, they claim to be able to process 2 GB of files (SA-FILE EE edition or even no file size restrictions), and the efficiency is also very good, is the programming language so much less efficient? I checked some information and thought they were all directly operating the file stream. In this way, the file size is not restricted. However, it is not absolutely perfect for foreigners. After aspupload processes large files, the memory usage is astonishing. Around 1 GB is common. As for SA-FILE although it is good but difficult to find the crack. Then we found two. Net Upload components, lion. Web. uploadmodule and aspnetupload, which are also operation file streams. However, the upload speed and CPU usage are not as good as the commercial components of foreigners. A test was conducted to upload 1 GB files in the LAN. The average upload speed of aspupload is 4.4 Mb/s, the CPU usage is 10-15, and the memory usage is 700 mb. SA-FILE is almost like this. The aspnetupload is only 1.5 m/s at the fastest, with an average of 700 K/s and CPU usage of 15-39. test environment: piii800, 100 m memory, and m lan. I think the slow speed of aspnetupload may be caused by hard disk writing while receiving files. The low cost of resource occupation is to reduce the transmission speed. But I also have to admire the foreign program. The CPU usage is so low ..... Iii. ASP. NET File Upload Problems We have encountered one or more problems when uploading large files using ASP. NET. Setting a large value of maxrequestlength does not completely solve the problem, because ASP. net blocks the entire file until it is loaded into the memory and then processes it. In fact, if the file is large, we often see that Internet Explorer displays "the page cannot be displayed-cannot find server or DNS error". It seems that this error cannot be caught. Why? Because this is a client side error, application_error on the server side cannot be handled. Iv. ASP. NET large file upload Solution 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. 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. Solution Principle: Httphandler is used to implement functions similar to ISAPI extention, process request information and send response ). Solution highlights: 1. httphandler or httpmodule A. The request object is intercepted before the Asp.net process processes the request. B. Read and Write Data in Parts C. Track the upload progress in real time and update the meta information. 2. Use the implicit httpworkerrequest to process the file stream using its getpreloadedentitybody and readentitybody methods. ========================================================== ================================== I have forgotten where the above description was found. It is clear about the uploading of large files in Asp.net. I just want to explain one problem here: In fact, if the file is large, we often see that Internet Explorer displays "the page cannot be displayed-cannot find server or DNS error". It seems that this error cannot be caught. Why? Because this is a client side error, application_error on the server side cannot be handled. I tried it many times and found that the error was indeed on the server side. This is my proof: 11:07:13 am aa8b180d-a91e-4734-938f-00c066b4993b: aa8b180d-a91e-4734-938f-00c066b4993b.doc 11/7/2005 11:08:07 am start upload ....... 11/7/2005 11:08:11 am httpmodule error ..... 11/7/2005 11:09:31 am start upload ....... 11/7/2005 11:09:44 am httpmodule error ..... 11/7/2005 11:10:43 am start upload ....... 11:10:46 am 55007: 49152 11/7/2005 11:10:46 am ----------------------------- 7d531c2e1705ac Two of them are because I uploaded a large file and the program encountered an error. This error is not handled using try and catch blocks, but in Private void webbupload_error (Object sender, eventargs E) { # Region function webbupload_error Webbtexttrace. tracemsg ("httpmodule error ....."); # Endregion This. Dispose (); } That is to say, when we upload a large file, the server quickly detects the file size and returns an error. It turns out that I can only upload half of the files each time. What is the problem? If we do not write the httpmodule on our own, the server has its own processing module. In this case, we can only upload small files. If the file server is too large, an error will occur. If we write the httpmodule ourselves, isn't this error necessarily true? Not necessarily, I encountered this problem several times during the test because I was processing the file stream or it was not an issue with Asp.net's httpmodul, but some exceptions (. net), which is exactly ours. the managed code on the. NET platform cannot catch exceptions, which can only be captured by the unmanaged module of IIS. Therefore, the returned result is an error not found on the server. Therefore, if such an error occurs and you write your own httpmodul module according to the above method, the problem cannot be solved, that is, it occurs in your module. net incompatibility exception, which causes the above error. The exceptions that cannot be captured by. Net can be affirmed: it must be a problem with your program. Therefore, be careful when detecting the code .. I have encountered several errors in these places: 1. An error occurred while reading data in a byte loop. 2. Zero division error at a time (this can be captured, but no. I don't know why ?) 3. Resource locking error. Specifically, I cannot remember what the error was, because each time it was just an error that could not be found by the server, I could only find the problem by searching the code manually, then I guess... There are some problems with the exception mechanism of. Net itself, especially in hosting compatibility. Well, I hope this article will help some people... |
Make the default Upload Component of Asp.net support progress bar reflectionAuthor: Date: 8:08:00
Http://blog.joycode.com/dotey/archive/2005/06/12/53557.aspx
For web-based uploads, in fact, there is no need to upload too many things. The default Upload Component of Asp.net is enough, and the failure in the ointment is that the upload progress is not reflected, so now we need to add Progress reflection based on the default upload in Asp.net.
With regard to the principles of Web upload, I have thoroughly analyzed the ASP no-component upload progress bar solution, ASP no-component upload with progress bars (continued), I have written a component-less upload progress bar for ASP, so I will not repeat it here. I believe many people have read the "ASP. net, the solution is to use the implicit httpworkerrequest, use its getpreloadedentitybody and readentitybody methods from IIS to ASP. the pipe created by net reads data in blocks, analyzes each block and stores it as a temporary file, which is relatively complicated.
To reflect the progress bar in real time, the core technology is to read uploaded data in blocks. When reading each data block, the number of uploaded parts is recorded, you can know the size of the uploaded file and the progress of the current Upload Based on the total size. The specific technique is to use the implied httpworkerrequest, and use its getpreloadedentitybody and readentitybody methods from IIS to ASP. in pipe created by net, data is read in blocks, but only in blocks and records the number of uploaded blocks. You do not need to analyze and process uploaded data, this is because the complicated work has been done by the Asp.net Upload Component.
According to the principle described above, the specific code is relatively simple. I wrote an example and used a special progress display page (Progress. aspx). It uses timed refresh (XMLHTTP, FF supported) to obtain the current upload progress information and reflect it on the upload page in real time.
Download the code (decompress the package and set the virtual directory to "Upload" for the web directory). Here, the progress bar is implemented by a script. The script code of the individual progress bar is as follows:
Http://www.webuc.net/myproject/progressbar/progressinfo.htm
Http://www.webuc.net/myproject/progressbar/progressbar.rar