zoukankan      html  css  js  c++  java
  • c# 下载文件封装方法

    一,普通下载(大文件会报内存错)

    /// <summary>
            /// 普通下载
            /// </summary>
            /// <param name="FileName">文件虚拟路径</param>
            ///  /// <param name="name">返回客户端名称</param>
            public static void DownLoadold(string FileName, string name)
            {
                string destFileName = FileName;
                if (System.IO.File.Exists(destFileName))
                {
                    try
                    {
                        FileInfo fi = new FileInfo(destFileName);
                        HttpContext.Current.Response.Clear();
                        HttpContext.Current.Response.ClearHeaders();
                        HttpContext.Current.Response.Buffer = false;
                        HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                        HttpContext.Current.Response.AppendHeader("Content-Length", fi.Length.ToString());
                        HttpContext.Current.Response.ContentType = "application/octet-stream";
                        HttpContext.Current.Response.WriteFile(destFileName);
                        HttpContext.Current.Response.Flush();
                        HttpContext.Current.Response.End();
                       
                    }
                    catch { }
                    finally
                    {
                        HttpContext.Current.Response.Close();
                        GC.Collect();
                    }
                }
            }

    二,分块下载

     /// <summary>
            /// 分块下载
            /// </summary>
            /// <param name="FileName">文件虚拟路径</param>
           /// <param name="name">文件虚拟路径</param>
            public static void DownLoad(string FileName, string name)
            {
                string filePath = FileName;
                long chunkSize = 204800;             //指定块大小 
                byte[] buffer = new byte[chunkSize]; //建立一个200K的缓冲区 
                long dataToRead = 0;                 //已读的字节数   
                FileStream stream = null;
                try
                {
                    //打开文件   
                    stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
                    dataToRead = stream.Length;
    
                    //添加Http头   
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));//HttpUtility.UrlEncode(Path.GetFileName(filePath))
                    HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString());
    
                    while (dataToRead > 0)
                    {
                        if (HttpContext.Current.Response.IsClientConnected)
                        {
                            int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize));
                            HttpContext.Current.Response.OutputStream.Write(buffer, 0, length);
                            HttpContext.Current.Response.Flush();
                            HttpContext.Current.Response.Clear();
                            dataToRead -= length;
                        }
                        else
                        {
                            dataToRead = -1; //防止client失去连接 
                        }
                    }
                }
                catch (Exception ex)
                {
                    HttpContext.Current.Response.Write("Error:" + ex.Message);
                }
                finally
                {
                    if (stream != null) stream.Close();
                    HttpContext.Current.Response.Close();
                }
            }

    或者

    public static void download(string fileName, string filePath)
    {
       System.IO.FileInfo fileInfo = new System.IO.FileInfo(filePath);
       if (fileInfo.Exists == true)
       {
         const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
         byte[] buffer = new byte[ChunkSize];
         Response.Clear();
         System.IO.FileStream iStream = System.IO.File.OpenRead(filePath);
         long dataLengthToRead = iStream.Length;//获取下载的文件总大小
         Response.ContentType = "application/octet-stream";
         Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName));
         while (dataLengthToRead > 0 && Response.IsClientConnected)
          {
              int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
              Response.OutputStream.Write(buffer, 0, lengthRead);
              Response.Flush();
             dataLengthToRead = dataLengthToRead - lengthRead;
          }
          Response.Close();
       }
    }
     
  • 相关阅读:
    Windows Power Shell
    一个自律的人有多可怕!
    Android之TextureView浅析
    BEGINNING SHAREPOINT&#174; 2013 DEVELOPMENT 第9章节--client对象模型和REST APIs概览 介绍SP2013中远程APIs
    敌兵布阵(线段树)
    kendo AutoComplete实现多筛选条件
    Android 65K问题之Multidex原理分析及NoClassDefFoundError的解决方法
    让我心碎的五道题
    输入一列数组,输出它的逆序数组
    centos下配置防火墙port失败
  • 原文地址:https://www.cnblogs.com/qingjiawen/p/14684574.html
Copyright © 2011-2022 走看看