首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

文件下载类

Posted on 2010-09-26 14:27  达奇  阅读(400)  评论(0编辑  收藏  举报

/// <summary>
    /// 文件下载类
    /// 调用1:DownLoadFile("/2003.xls", null);
    /// 调用2:DownLoadFile("/2003.xls", "");
    /// 调用3:DownLoadFile("/2003.xls", "temp.xls");
    /// </summary>
    /// <param name="URL">文件路径(格式:/upload/2003.xls)</param>
    /// <param name="filename">自定义文件名(不想自定义文件名请传[ "" or null ] )</param>
    public void DownLoadFile(string URL, string filename)
    {
        string filePath = System.Web.HttpContext.Current.Server.MapPath("./") + URL;//路径
        if (string.IsNullOrEmpty(filename))
            filename = System.IO.Path.GetFileName(filePath);
        //以字符流的形式下载文件
        System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
        byte[] bytes = new byte[(int)fs.Length];
        fs.Read(bytes, 0, bytes.Length);
        fs.Close();
        System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";
        //通知浏览器下载文件而不是打开
        System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filename));
        System.Web.HttpContext.Current.Response.BinaryWrite(bytes);
        System.Web.HttpContext.Current.Response.Flush();
        System.Web.HttpContext.Current.Response.End();
    }