//cs文件
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
public partial class DownLoad : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string fileName = Request.QueryString["FileName"];
if (fileName != "")
{
//获取文件路径
string path = Server.MapPath("Upload/") + fileName;
//初始化 FileInfo 类的实例,它作为文件路径的包装
FileInfo fi = new FileInfo(path);
//判断文件是否存在
if (fi.Exists)
{
//将文件保存到本机上
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
Response.AddHeader("Content-Length", fi.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Filter.Close();
Response.WriteFile(fi.FullName);
Response.End();
}
}
else
{
Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>alert('找不到所要下载的文件!');{location.href='Default.aspx'}</script>");
}
}
}
}
//aspx页面中
<asp:DataList ID="dlCharge" runat="server" Width="543px" >
<ItemTemplate>
<table align="center" cellpadding="0" cellspacing="0" width="543">
<tr>
<td>
<span class="hongcu">『<%# DataBinder.Eval(Container.DataItem,"Title") %>』</span><span class="chengse"><%# DataBinder.Eval(Container.DataItem,"Title") %></span>
<span class="huise1">
<%#DataBinder.Eval(Container.DataItem,"date") %>
</span>
<br />
<span class="shenlan">
<a href="DownLoad.aspx?FileName=<%#DataBinder.Eval(Container.DataItem,"FileName") %> "><%#DataBinder.Eval(Container.DataItem,"FileName") %></a>
</span>
<br />
</td>
</tr>
<tr style="color: #000000">
<td align="center">
<img height="1" src="images/longline.gif" width="525" /></td>
</tr>
<tr style="color: #000000">
<td height="10">
</td>
</tr>
</table>
</ItemTemplate>
</asp:DataList>
来源:https://www.cnblogs.com/QiuJL/archive/2011/08/11/4524281.html