默认情况文件下载,直接链接指向文件的地址即可,但是有些情况下浏览器而是直接打开了文件。例如txt文件的下载,火狐浏览器直接打开了txt文件,并不是下载了txt,txt其实被浏览器缓存了起来。

pdf同样如此,一般电脑都安装了Adobe Reader 这个pdf的阅读器,当浏览器下载pdf的文件时候,默认依然是浏览器打开了该pdf文件 而不是下载该pdf文件。

下面的代码就是 默认不让浏览器打开文件,而且下载文件

Download.ashx



<%@ WebHandler Language="C#" Class="Download" %>

using System;
using System.Web;
using System.IO;

public class Download : IHttpHandler {

public void ProcessRequest (HttpContext context) {
context.Response.ContentType = "text/plain";

string path = context.Server.UrlDecode(context.Request.QueryString["path"].ToString());

string fileName = Path.GetFileName(path);//文件名

string filePath = context.Server.MapPath(path);//路径

if (File.Exists(filePath))
{
//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open);
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
context.Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
context.Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
context.Response.BinaryWrite(bytes);
context.Response.Flush();
context.Response.End();
}
else
{
context.Response.Write("未上传文件!!");
context.Response.End();
}


}

public bool IsReusable {
get {
return false;
}
}

}