//得到下载文件的ContentType
public string GetFileContentType(string filename)
{
string[] array = filename.Split('.');
string result = string.Empty;
string suffix = "." + array[array.Length - 1];
RegistryKey rg = Microsoft.Win32.Registry.ClassesRoot.OpenSubKey(suffix);
object obj = rg.GetValue("Content Type");
result = obj != null ? obj.ToString() : string.Empty;
rg.Close();
return result;
}
public bool DownloadFiles(string filePath,string fileName,out long filelengh)
{
filelengh = 0;
try
{
//string fileName = "asd.txt";//客户端保存的文件名
//string filePath = Server.MapPath("DownLoad/aaa.txt");//路径
FileInfo fileInfo = new FileInfo(filePath); //filePath为文件在服务器的全路径,包含文件名。
Response.Clear();
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment;filename=" + fileName);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
filelengh = fileInfo.Length;
Response.AddHeader("Content-Transfer-Encoding", "binary");
Response.Charset = "GB2312";
Response.ContentType = GetFileContentType(fileName); //调用下载文件的ContentType
Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
Response.WriteFile(fileInfo.FullName);
Response.Flush();
Response.End();
return true;
}
catch (Exception)
{
return false;
}
}
调用方法:
if (!IsPostBack)
{
string type = Request.QueryString["filetype"].ToString();
string path =string.Empty;
switch (type)
{
case "chengguo":
path = "~\\Files\\";
break;
case "data":
path = "~\\DataFiles\\";
break;
default:
break;
}
string name = Request.QueryString["filename"].ToString();
string fullpath = Server.MapPath(path+name);
long filelength;
bool su=DownloadFiles(fullpath, name, out filelength); //调用方法
if (!su)
{
ClientScript.RegisterStartupScript(GetType(), "Message", "<SCRIPT LANGUAGE='javascript'>alert('该文件不存在,或下载出错!');</script>");
}
}