Mobile Project Development notes (response. writefile () in Asp.net to download files)

Source: Internet
Author: User

Many projects often involve file upload and download. File Upload can change the appearance of the upload control,

See http://www.cnblogs.com/Charles2008/archive/2008/07/20/1247084.html

 

After an object is uploaded, it involves downloading the object. So how can I download files in Asp.net? This is my topic. File Download is to download the files uploaded from the client to the local device. There are several problems involved: where the uploaded files are stored. How many storage methods are available?

Generally, the uploaded files are stored on the server, which can be an FTP server or a Web server, depending on the actual situation. However, the storage methods are similar to the following:

1. Save it to the database on the server. (Binary format)

2. Save it to the XML file on the server. (Suitable for small file storage)

3. Save it to the folder on the server disk. (More common)

However, in the current mobile project development, I want to save the file to a folder on the server: This leads to several problems to be solved:

1. If the user uploads two different files with the same file name, for example, XXX project report. Wouldn't it overwrite the last uploaded file.

Of course, this is not the case. If different users upload files with the same file name, then, the final file uploaded to the server is the last one that overwrites the previous one. Isn't it a serious bug !!!.

Solution: this file is of course a good solution, that is, when the file is uploaded to the server, rename the file and use guid to implement uniqueness. This ensures that the file names uploaded to the server by the same user and different users are different, so that the files can exist in a folder on the server at the same time. This solves the problem. However, we also need to consider the following issues:

2. Because the guid is used for uploading files to the server, the file name downloaded from the file address is different from the uploaded file name. This provides a poor user experience.

Solution: To solve this problem, we thought of using response. writefile () to implement:

The following is the reference code:

 

<Asp: gridview id = "gridview1" width = "50%" runat = "server" autogeneratecolumns = "false"
Emptydatatext = "<tr> <TH class = 'gridhead' scope = 'col'> attachment name </Th> <TH class = 'gridhead' scope = 'col'> uploaded by </Th> <TH class = 'gridhead' scope = 'col'> upload time </Th> </tr> ">
<Columns>
<Asp: templatefield headertext = "attachment name">
<Itemtemplate>
<Span>
<% # Databinder. eval (container. dataitem, "originallyfilename") %>
</Span>
<A href = '<% # "downfile. aspx? Name = "+ databinder. eval (container. dataitem, "originallyfilename "). tostring () + "& Path =" + databinder. eval (container. dataitem, "filepath") %> 'target = "_ Self"> download </a>
</Itemtemplate>
</ASP: templatefield>
<Asp: boundfield datafield = "inuser" headertext = "Uploader">
<Itemstyle cssclass = "itemstyle" horizontalalign = "center"/>
<Headerstyle cssclass = "gridheader"/>
</ASP: boundfield>
<Asp: boundfield datafield = "indate" headertext = "Upload time" dataformatstring = "{0: yyyy-mm-dd }"
Htmlencode = "false">
<Itemstyle cssclass = "itemstyle" horizontalalign = "center"/>
<Headerstyle cssclass = "gridheader"/>
</ASP: boundfield>
<Asp: templatefield headertext = "operation">
<Itemtemplate>
<Asp: imagebutton runat = "server" id = "btndelete" imageurl = "~ /Images/btndel.gif "alternatetext =" delete"
Imagealign = "Middle"/>
</Itemtemplate>
<Itemstyle cssclass = "itemstyle" horizontalalign = "center"/>
<Headerstyle cssclass = "gridheader"/>
</ASP: templatefield>
</Columns>
</ASP: gridview>

The above is the aspx code: the download link requires an originallyfilename, that is, the file name to be uploaded. Filepath is the file path saved to the server after the file is uploaded. (Including file names ). The original file name and the file path saved to the server are passed to the downfile. ASPX page. Let's take a look at the code on the downfile. ASPX page:

 

 

Protected void page_load (Object sender, eventargs E)
{
String guidname = request. querystring ["path"];
String reallyname = request. querystring ["name"];
String fullfilename = server. mappath ("~ /Uploads/"+ guidname );
Fileinfo info = new fileinfo (fullfilename );
Response. Clear ();
Response. clearheaders ();
Response. Buffer = false;
Response. contenttype = "application/octet-stream ";
Response. appendheader ("content-disposition", "attachment; filename =" + httputility. urlencode (reallyname, system. text. encoding. utf8 ). replace ("+", "% 20 "));
Response. appendheader ("Content-Length", info. length. tostring ());
Response. writefile (fullfilename );
Response. Flush ();
Response. End ();
}

 

Note the following:

1. Use System. Text. encoding. UTF to support Chinese characters. (Otherwise, the file name containing the Chinese name downloaded in the file name becomes garbled)

2. replace "+" with "(Space), and" + "with httputility. after urlencode encoding, the space is converted to "+". However, "+" cannot be understood by the browser as space and cannot be decoded. Therefore, you need to manually change "+" to space (% 20) (because the character encoding of spaces is recognized as "% 20" in the browser ). this is a small bug that is very easy to ignore. Fortunately, the tester found it early and I corrected it using the replace method.

The page effect is as follows:

 

 

 

When you click the download link with the left mouse button:

 

When you right-click and save as a file, the download dialog box shown above will also appear: the uploaded file name is xmlserializer.txt, And the downloaded file name is also resolved by the xmlserializer.txt problem.

 

Download files are generally implemented using tag a, which links to a new page, as shown in the preceding figure (downfile. ASPX page). If you connect to the current page, onclick is used to trigger server-side events for download. In this case, you can only click Download by clicking the left mouse button, but not by right-clicking save as download. (You can give it a try)

I will not demonstrate it here.

 

Finally, I hope this article will be helpful to my friends. helping others is my greatest pleasure. Of course, I also hope that my friends can point out issues and communicate with each other. Thank you.

MSN: Charles.C.Chen@newegg.net

Email: Charles.C.Chen@newegg.com

 

 

 

 

 

In addition, the download method was run in the project. Soon the tester found the problem: when the file is too large, the download was slow, or even failed to download the file. I have optimized the code by referring to relevant materials. For sharing with friends.

 

Response. writefile () principle: the server first loads all the content into the memory, and then outputs

Therefore, if a large file is encountered and the memory on the server is relatively small, the file cannot be downloaded. Therefore, you can use filestream to directly write it to the Web output stream.

We recommend that you use the following code to achieve multipart file implementation:

 

Code
Response. bufferoutput = false;

Response. Clear ();
Response. appendheader ("content-disposition", (@ "inline; filename =" + "FILENAME "));
Response. contenttype = "application/unknown ";
Response. cachecontrol = "private ";
Stream STM = new filestream ("D: \ Download \ test.txt", filemode. Open );

Binaryreader BR = new binaryreader (STM );

Byte [] bytes;

For (int64 x = 0; x <(Br. basestream. Length/10000 + 1); X ++)
{
Bytes = Br. readbytes (10000 );
Response. binarywrite (bytes );
}

STM. Close ();

Note: If the downloaded file size is only 0 kb, an exception occurs when the program calls the above Code:

Therefore, we should first determine the file size for comprehensive consideration. When the file size is 0, we should use response. writefile (). If it is not 0, use the following code to implement multipart download.

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.