Web-based file upload and download summary: File upload and download are very important in the network of two applications, this article describes the use of ASP. NET control to implement the basic method of file upload. solves various problems when uploading large files, and gives several solutions and techniques. In addition, the download file is implemented in binary read-write mode.
1 Introduction File Upload and download is very important in the network of two applications. Its implementation methods are mainly FTP and HTTP mode, FTP (file Transfer Protocol) refers to the files Transfer protocol, mainly used to transfer files on the network. Although the file transfer is stable, the system resource occupancy rate is low, the file size is not limited, but the deployment of the server is more complex, need to use specific software to complete the upload and download, and a single function, permissions set complex, generally used for professional file transfer, for the average user is not high practicality. HTTP (Hyper Text Transfer Protocol) refers to Hypertext Transfer Protocol, which is the most widely used network transmission protocol on the Internet. All WWW pages are subject to this standard. HTTP was originally designed to provide a way to publish and receive HTML pages. Compared to FTP, HTTP uses the browser as the client software, user-friendly interface, simple operation, through the Web Form mechanism to achieve file upload, the use of hyperlinks and binary read and write methods to achieve file download. Because the http file upload and download can be integrated in the Web page, easy to use, more practical, has been widely used in forums, e-mail, network hard disk and other practical applications. This article mainly describes the use of ASP to complete the file upload and download.
2 upload implementation before ASP. http file upload is a complex thing to do. As Microsoft's next-generation Web-based program development platform, HtmlInputFile provides a special control for file uploads, which can be easily uploaded using this control. The syntax for the control is: <input id= "control name" type= "file" runat= "Server" > The syntax for saving the uploaded file under the server specified folder is: control name. Postedfile.saveas (server side physical path) you can also use the ContentLength, ContentType, and filename properties to get the file size, file type, and path to the client, respectively, to the file type, size, The file name and so on special limit, guarantees the system security and the stability. The specific upload code is as follows (the code listed in this article uses the C # language):
For the GetFileName method of the System.IO.Path class, import the System.IO namespace < namespace= "System.IO"%>
<script language= "C #" runat= "server" > private void Enter_click (Object Sender,eventargs e) {String filename, filepath; The Path.getfilename method can get the file name from any one of the path strings filename= path.getfilename (uploadfile. Postedfile.filename); FilePath is the physical path of the server-side save upload file filepath= server.mappath ("upload") + filename; Save the uploaded file UploadFile. Postedfile.saveas (filepath); The upload file details message is shown below. InnerHtml = "File has been successfully uploaded, details are as follows"; Message. InnerHtml + = "<br> save path:" + filepath; Message. InnerHtml + = "<br> file name:" + filename; Message. InnerHtml + = "<br> File size:" + uploadfile. Postedfile.contentlength + "bytes"; Message. InnerHtml + = "<br> file type:" + uploadfile. Posted-file.contenttype; Message. InnerHtml + = "<br> Client path:" + UploadFile. Postedfile.filename; Message. InnerHtml + = "<br><a href=//upload/" + filename + "//> view file </a>";} </script>
Web. config file <system.web>
IServiceProvider provider= (IServiceProvider) httpcontext.current; HttpWorkerRequest request1= (HttpWorkerRequest) provider. Get-service (typeof (HttpWorkerRequest)); Create buffer for uploading data byte[]; Returns the part of the HTTP request body that has been read buffer= Request1. Getpreloadedentitybody (); If it is an attachment upload if (! request1. Isentireentitybodyispreloaded ()) {//chunked size Int n=1024;//define temporary buffer byte[] tempbuff=new byte[n];//loop block read until all data reads end while (r Equest1. Readentitybody (tempbuff,n) >0) {//To analyze and store data read into the temporary buffer?}}
By using this method, the uploading progress can be achieved through the analysis of the block data. This method is more efficient, not limited by the size of the server memory, tested, in the preparation of 512MB memory on the server can be stable upload 1GB data files, but the implementation method is relatively complex. Finally, there is another option that is implemented using ASP. NET-based third-party components such as aspnetupload. This method is simple, no upload file size limit, stability, upload efficiency and other aspects are very good, and friendly interface, generally provide upload progress indicator and other additional functions. But the problem is that good components are generally commercial software and require a fee to be used.
3 Download Implementation the implementation of the download in the Web page is much simpler than the upload, the General page is used to create a hyperlink to the file to be downloaded, after the client clicked the hyperlink, The download dialog box pops up to download. This method is suitable for files with RAR or zip compression, but if the source file is a common format such as doc, TXT, BMP, and the client has associated the files in these formats, the download window will not pop up, but the file is opened directly in the current location. For some novice users, the system is considered to be a problem, did not complete the download, affecting the normal use of the system. In order to solve this problem, it can be implemented by binary read/write method, using the Read () method of the FileStream object to read the file into a byte array, and then output to the client with the Response.BinaryWrite () method. Specific code:
FilePath for the specific path of the file to be downloaded FileStream fs = new FileStream (FilePath, FileMode.Open); Build buffer byte[] bytes = new byte[(int) fs. Length]; Read file to buffer fs. Read (bytes, 0, bytes. Length); Fs. Close (); Response.Clear (); Output to the browser, first indicate ContentType Response.ContentType = "Application/octet-stream"; Add the file name to the output stream and make the necessary encoding Response.AddHeader ("content-disposition", "attachment"; Filename= "+httputility.urlencode (FI. name,system.text.encoding.gb2312). Replace ("+", "")); Output binary file Response.BinaryWrite (bytes); Response.End (); Using this method, regardless of the type of file, when you want to download it will pop up the select window to let the user confirm "download" or "open". 4 conclusion using the ASP. NET control can be easier to implement file upload and download, but after all, HTTP is not specifically used for file transfer, so there are a lot of shortcomings. For example: server memory consumption is quite high, especially when uploading, downloading files large. Therefore, if you want to do large files (for example, more than 2G) upload download, the user community is relatively professional, or use FTP more appropriate. But for the requirements of simple operation, user-friendly interface and the amount of file transfer is not large, the method described above is still a great advantage and practicality.
#asp. NET Technology