使用超链接直接指定要下载的文件

文件下载
-》使用超链接直接指定要下载的文件
能被浏览器解析的文会被显示
不能被浏览器解析的文件会被下载
-》实现:无论文件格式,都不使用浏览器显示,完成下载
指向一般处理程序,文件地址作为参数
修改响应头:ContentType = "application/octet-stream";
设置头信息:AddHeader("Content-Disposition", "attachment; filename=\"文件名\";");
输出文件:context.Response.WriteFile(文件地址);
-》提示:如果中文文件名乱码,可以进行url编码
HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
返回一个字符串,作为文件的名字

public class Download : IHttpHandler
{

public void ProcessRequest(HttpContext context)
{
//提示:如果中文文件名乱码,可以进行url编码
//HttpUtility.UrlEncode(filename, System.Text.Encoding.UTF8);
//返回一个字符串,作为文件的名字

string f = context.Request["f"];

context.Response.ContentType = "application/octet-stream";
context.Response.AddHeader("Content-Disposition", "attachment; filename=\""+f+"\";");//%ab%12

context.Response.WriteFile(AppDomain.CurrentDomain.BaseDirectory+f);
}

public bool IsReusable
{
get
{
return false;
}
}
}

猜你喜欢

转载自www.cnblogs.com/jiangyunfeng/p/11122478.html