码迷,mamicode.com
首页 > 其他好文 > 详细

文件下载界面

时间:2016-08-25 23:37:32      阅读:299      评论:0      收藏:0      [点我收藏+]

标签:

public bool DwonLoadFile(string fileName,string filePath)
        {
            System.IO.Stream iStream = null;

            byte[] buffer = new Byte[10240];

            int length;

            long dataToRead;

            try
            {
                string filepath = HttpContext.Current.Server.MapPath("~/") + filePath; //待下载的文件路径

                iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open,
                    FileAccess.Read, FileShare.Read);
                Response.Clear();

                dataToRead = iStream.Length;

                long p = 0;
                if (Request.Headers["Range"] != null)
                {
                    Response.StatusCode = 206;
                    p = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", ""));
                }
                if (p != 0)
                {
                    Response.AddHeader("Content-Range", "bytes " + p.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString());
                }
                Response.AddHeader("Content-Length", ((long)(dataToRead - p)).ToString());
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment; filename=" + System.Web.HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding(65001).GetBytes(Path.GetFileName(fileName))));

                iStream.Position = p;
                dataToRead = dataToRead - p;

                while (dataToRead > 0)
                {
                    if (Response.IsClientConnected)
                    {
                        length = iStream.Read(buffer, 0, 10240);

                        Response.OutputStream.Write(buffer, 0, length);
                        Response.Flush();

                        buffer = new Byte[10240];
                        dataToRead = dataToRead - length;
                    }
                    else
                    {
                        dataToRead = -1;
                    }
                }
            }
            catch (Exception ex)
            {
                return false;

            }
            finally
            {
                if (iStream != null)
                {
                    iStream.Close();
                }
                Response.End();
            }
            return true;
        }

参考链接:http://www.cnblogs.com/liping13599168/archive/2009/02/08/1386111.html

文件下载界面

标签:

原文地址:http://www.cnblogs.com/KingUp/p/5808384.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!