我现在是这样做的,在保存文件到数据库的时候,用一个专门的字段存储文件的后缀,从数据库读出来,判断一下文件类型,给Response.ContentType的属性赋值,代码如下:
//根据文件的后缀名返回处理文件的程序头。
private string open_file_application(string str_file_type)
{
string str_result="";
switch (str_file_type)
{
//word文档
case "doc":
{
str_result="application/msword";
break;
}
//文本文档
case "txt":
{
str_result="text/plain";
break;
}
//gif图像文档
case "gif":
{
str_result="image/gif";
break;
}
//Excel文档
case "xls":
{
str_result="application/vnd.ms-excel";
break;
}
//网页文档
case "html":
{
str_result="text/html";
break;
}
case "htm":
{
str_result="text/html";
break;
}
//无法识别的文档
default:
{
str_result="Application/unknown";
break;
}
}
return str_result;
}

解决方案 »

  1.   

    chyich() :我也是照你说得做的,可是我输出的不是我想要的文件,却是我所在页面的名字。比如我想输出test.zip 实际输出的却是download.aspx WHY???
      

  2.   

    显示pdf文件:
    private void showfile(string commandstr)
    {
    string filesize,filename;
    byte[] content;
    SqlConnection conn=new SqlConnection(con);
    SqlCommand cmd=new SqlCommand(commandstr,conn);
    conn.Open();
    SqlDataReader sr;
    sr=cmd.ExecuteReader();
    if(sr.Read())
    {
    content=(byte[])sr["SC_image"];
    filesize=content.Length.ToString();
    filename=Common.Util.Get_filename(sr["source_file_name"].ToString());
    if(sr["image_type"].ToString()=="application/pdf")
    filename="x.pdf";
    Response.ContentType = sr["image_type"].ToString();
    Response.AddHeader("Content-Length",filesize);
    Response.AddHeader("Content-Disposition", "inline;filename="+filename);
    Response.BinaryWrite(content);
    }
    sr.Close();
    conn.Close();
    }
      

  3.   

    blackcourser(黑骏马):当文件名是中文时,输出的文件名是乱码,而纯英文则没事,如何解决?
      

  4.   

    配合上述那个函数,可以用来打开指定路径和文件名的文件。你对比看一下你的程序://打开指定路径的文件,参数str_file_path_name表生成文件的路径及文件名;
    public void openfile(string str_file_path_name)
    {
    System.IO.FileInfo MyFileInfo;
    long StartPos = 0, FileSize; 
    string str_extension;

    MyFileInfo = new System.IO.FileInfo(str_file_path_name);
    str_extension=MyFileInfo.Extension;
    str_extension=str_extension.Substring(1);
    FileSize = MyFileInfo.Length;
    HttpContext.Current.Response.Clear();
    //根据不同的类型设置ContentType属性,以便用相应程序打开文件。
    HttpContext.Current.Response.ContentType=open_file_application(str_extension);
    //打开文件
    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline;filename='" + str_file_path_name + "'");
    HttpContext.Current.Response.WriteFile(str_file_path_name, StartPos, FileSize);
    HttpContext.Current.Response.End(); }