文件下载

<a href="uploadfiles/1.txt"></a>

HttpHandler是对请求的响应,可以输出普通的html内容,也可以输出图片、也可以输出一个文件(下载)

HttpHandler输出的是html/txt/jpeg等类型的信息,那么浏览器会直接显示,如果希望弹出保存对话框,则需要添加Header
string encodeFileName=HttpUtility.UrlEncode("ss.avi");
Response.AddHeader("Content-Disposition",string.Format("attachment;filename="{0}"",encodeFileName));
filename后为编码后的文件名。filename段为建议的保存文件名。

但是不安全


string strFileName=HttpUtility.UrlEncode("fName");
if(!string.IsNullOrEmpty(strFileName))
{
string encodeFileName=HttpUtility.UrlEncode(strFileName);
//添加Content-Disposition,告诉浏览器使用另存为的方式下载文件。
context.Response.AddHeader("Content-Disposition",string.Format("attachment;filename="{0}"",encodeFileName));
string strFilePath=context.Server.MapPath("uploadfiles/"+strFileName);
context.Response.WriteFile(strFilePath);
}
else
{
context.Response.Write("参数有误!");
}

原文地址:https://www.cnblogs.com/buzhidaojiaoshenme/p/7069019.html