利用repeater綁定下載地址並點擊下載(避免中文文件名亂碼)
aspx
<asp:Repeater ID="Repeater1" runat="server">
<HeaderTemplate>
<table>
<tr>
</HeaderTemplate>
<ItemTemplate>
<tr>
<td >
<a href='../download.ashx?url=<%# Server.UrlEncode(Eval
("FilePath").ToString())%>'>
<%#eval_r("FileName")%></a>
</td>
</ItemTemplate>
<FooterTemplate>
</tr></table></FooterTemplate>
</asp:Repeater>
download.ashx
using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
namespace Web.UCenter
{
/// <summary>
/// $codebehindclassname$ 的摘要說明
/// </summary>
[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class download : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
try
{
string path = context.Request.QueryString["url"].ToString();
System.IO.FileInfo file = new System.IO.FileInfo(path);
context.Response.Clear();
context.Response.Charset = "GB2312";
context.Response.ContentEncoding = System.Text.Encoding.UTF8;
// 添加頭信息,為"文件下載/另存為"對話框指定默認文件名
context.Response.AddHeader
("Content-Disposition",
"attachment; filename="
+
System.Web.HttpUtility.UrlEncode
(file.Name,System.Text.Encoding.UTF8));// 防止中文名有亂碼
// 添加頭信息,指定文件大小,讓瀏覽器能夠顯示下載進度
context.Response.AddHeader("Content-Length", file.Length.ToString());
//// 指定返回的是一個不能被客戶端讀取的流,必須被下載
//context.Response.ContentType = "application/ms-excel";
// 把文件流發送到客戶端
context.Response.WriteFile(file.FullName);
// 停止頁麵的執行
context.Response.End();
}
catch
{
context.Response.Write("您下載的資源不存在!");
}
}
public bool IsReusable
{
get
{
return false;
}
}
}
}
注意點:我在數據庫存儲的文件路徑是加server.map的絕對路徑。實際下載的時候根據實際情況修改代碼。
最後更新:2017-04-02 06:52:24