asp.net心得之实现下载功能

闲话不扯,直接上码,至于下载的方式,可以直接决定,按钮、链接等等都是可行的,后端代码,如果你有心,也可以做成类文件。

 

<asp:Button ID="btnDownLoad" runat="server" Text="下载"  onclick="btnDownLoad_Click" />

 

 1 using System;
2 using System.IO;
3 using System.Web;
4
5 public partial class UserControls_Default : System.Web.UI.Page
6 {
7 protected void Page_Load(object sender, EventArgs e)
8 {
9
10 }
11 public void DownLoadFile(string fileName, byte[] bytes)
12 {
13 HttpResponse Response = System.Web.HttpContext.Current.Response;
14 HttpRequest Request = System.Web.HttpContext.Current.Request;
15 try
16 {
17 Response.Clear();
18 Response.ClearHeaders();
19 Response.Expires = -1;
20 Response.AddHeader("Accept-Ranges", "bytes");
21 Response.Buffer = false;
22 long startBytes = 0;
23 if (Request.Headers["Range"] != null)
24 {
25 Response.StatusCode = 206;
26 string[] range = Request.Headers["Range"].Split(new char[] { '=', '-' });
27 startBytes = Convert.ToInt64(range[1]);
28 }
29 Response.AddHeader("Content-Length", (bytes.Length - startBytes).ToString());
30 if (startBytes != 0)
31 {
32 Response.AddHeader("Content-Range", string.Format(" bytes {0}-{1}/{2}", startBytes, bytes.Length - 1, bytes.Length));
33 }
34 Response.AddHeader("Connection", "Keep-Alive");
35 Response.ContentType = "application/octet-stream";
36 Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
37 Response.BinaryWrite(bytes);
38 Response.Flush();
39 //Response.End();
40 System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
41
42 }
43 catch
44 {
45 Response.Close();
46 }
47 finally
48 {
49 Response.Close();
50 }
51 }
52
53 /// <summary>
54 /// 下载按钮操作
55 /// </summary>
56 /// <param name="sender"></param>
57 /// <param name="e"></param>
58 protected void btnDownLoad_Click(object sender, EventArgs e)
59 {
60 string fileName = "ExampleExcel.xls";//客户端保存的文件名
61 string filePath = Server.MapPath("../DownLoad/Example.xls");//路径以字符流的形式下载文件
62 FileStream fs = new FileStream(filePath, FileMode.Open);
63 byte[] bytes = new byte[(int)fs.Length];
64 fs.Read(bytes, 0, bytes.Length);
65 fs.Close();
66 DownLoadFile(fileName, bytes);
67 }
68 }

 

posted on 2012-03-10 11:15  zhangtao1212  阅读(222)  评论(0编辑  收藏  举报

导航