asp.Net心得の実現ダウンロード機能
10508 ワード
暇な話はしないで、直接コードをつけて、ダウンロードの方式について、直接決定することができて、ボタン、リンクなどはすべて実行することができて、バックエンドのコード、もしあなたが気があれば、クラスのファイルを作ることができます.
<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 }