一念行者
一切有为法,皆梦幻泡影。如露亦如电,应作如是观。笑着面对,不去埋怨。悠然,随心,随性,随缘。注定让一生改变的,只在百年后,那一朵花开的时间。
        /// <summary>
        /// 文件下载
        /// </summary>
        /// <param name="filePath">物理路径(推荐使用Server.MapPath)</param>
        /// <param name="isBinaryWrite">是否采用二进制的方式输出(一般为false,对某些特殊的文件如pdf可设置为true)</param>
        public static void OutPutFile(string filePath, bool isBinaryWrite)
        {
            if (string.IsNullOrEmpty(filePath))
                return;
            FileInfo fi = new FileInfo(filePath);
            if (fi.Exists)
            {
                System.IO.Stream iStream = null;
                byte[] buffer = new Byte[10000];
                int length;
                long dataToRead;
                string filename = System.IO.Path.GetFileName(filePath);
                try
                {
                    iStream = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read);
                    dataToRead = iStream.Length;
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
                    while (dataToRead > 0)
                    {
                        if (HttpContext.Current.Response.IsClientConnected)
                        {
                            length = iStream.Read(buffer, 0, 4096);
                            if (isBinaryWrite == false)
                                HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                            else
                                HttpContext.Current.Response.BinaryWrite(buffer);
                            HttpContext.Current.Response.Flush();
                            buffer = new Byte[4096];
                            dataToRead = dataToRead - length;
                        }
                        else
                        {
                            dataToRead = -1;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //
                }
                finally
                {
                    if (iStream != null)
                    {
                        iStream.Close();
                    }
                }
            }
        }
View Code
posted on 2013-05-21 11:17  一念行者  阅读(675)  评论(0编辑  收藏  举报