分享一个asp.net支持firefox,google,ie的Response下载

来源:互联网 发布:淘宝大学怎么退订 编辑:程序博客网 时间:2024/05/16 06:53

 

其实这个下载是在简单的下载的基础上,做了一个浏览器的判断


/// <summary>

    /// Response.AddHeader实现下载
    /// </summary>
    /// <param name="filePath">完整的文件路径</param>
    /// <param name="fileName">文件名</param>
    private void DownFile(string filePath, string fileName)
    {
     
        ///、判断浏览器类型
        if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("msie") > -1)
        {


            fileName = HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8);
        }


        if (HttpContext.Current.Request.UserAgent.ToLower().IndexOf("firefox") > -1)
        {
            fileName = "\"" + fileName + "\"";
        }
        else
        {
            fileName = "\"" + fileName + "\"";
        }


        FileInfo fileInfo = new FileInfo(filePath);
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ClearContent();
        HttpContext.Current.Response.ClearHeaders();
    
        HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + formatString(fileName));//\"" + fileName + "\""




        HttpContext.Current.Response.AddHeader("Content-Length", fileInfo.Length.ToString());
        HttpContext.Current.Response.AddHeader("Content-Transfer-Encoding", "binary");
        HttpContext.Current.Response.ContentType = "application/octet-stream";
        HttpContext.Current.Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
        HttpContext.Current.Response.WriteFile(fileInfo.FullName);


        HttpContext.Current.Response.Flush();
        HttpContext.Current.Response.End();
    }


    private string formatString(string str)
    {
        str = str.Replace("+", " ");


        return str;

    }



以上就是所有代码

转自:咖啡之念 http://www.aicoffees.com

0 0