.NET客户端下载SQL Server数据库中文件流保存的大电子文件方法(不会报内存溢出异常)

时间:2023-03-21 22:51:26

                    .NET客户端下载SQL Server数据库中文件流保存的大电子文件方法(不会报内存溢出异常)

前段时间项目使用一次性读去SQL Server中保存的电子文件的文件流然后返回给客户端保存下载电子文件,在电子文件超过一定的大小的时候出现可恶的内存溢出!各种百度、google还是没找到解决的方法,最后不得不找微软的技术专家一起来解决大电子文件通过客户端浏览器下载这个异常,经过一段时间后找到一个理想的方案如下,性能虽然不高,但是基本能解决问题了,方法如下:

1.通过DataReader的方式来获取数据库中保存的电子文件的二进制流

public SqlDataReader GetFile(int fileID)
        {
            SqlDataReader myReader = ExecuteReader("select FileName,FileSize,FileContext from T_File where ID =" + fileID);
            return myReader;
        }

2.执行查询SqlDataReader的方法也有一个需要注意的地方, SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);

CommandBehavior.SequentialAccess的解释是提供一种方法,以便DataReader处理包含大二进制值的数据列,SequentialAccess不是加载整行,而是将DataReader

作为流来加载,然后可以使用GetBytes或者GetChars方法来读取指定位置的的字节并返回正在读取的数据的缓冲区的大小;

/// <summary>
        /// 执行查询语句,返回SqlDataReader
        /// </summary>
        /// <param name="strSql">查询语句</param>
        /// <returns>文件名称</returns>
        public static SqlDataReader ExecuteReader(string strSql)
        {
            SqlConnection connection = new SqlConnection(connectionString);
            SqlCommand cmd = new SqlCommand(strSql, connection);
            try
            {
                connection.Open();
                SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                return myReader;
            }
            catch (System.Data.SqlClient.SqlException e)
            {
                throw e;
            }
        }

3.读取到电子文件的DataReader后,以下是下载方法:

    SqlDataReader reader = GetFile(attaID);

string fileName = "";
                int bufferSize = 102400;//每次读取的缓冲区大小100KB
                byte[] outByte = new byte[bufferSize];
                int retval;//返回的值
                int startIndex = 0;//开始读取的位置
                string length;
                bool more = true;
                try
                {
                    reader.Read();//开始读取
                    fileName = reader.GetString(0);
                    length = reader.GetString(1);
                    length = (double.Parse(length) * 1024).ToString();
                    Response.Clear();//这里能解决64位windows Server2008服务器和2003服务器下载要求输入密码的问题
                    Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
                    Response.AddHeader("Content-Length", length);
                    Response.AddHeader("Content-Transfer-Encoding", "binary");
                    Response.ContentType = "application/octet-stream";
                    Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
                    do
                    {
                        retval = (int)reader.GetBytes(2, startIndex, outByte, 0, bufferSize);
                        if (Response.IsClientConnected)//判断客户端是否一直处于连接状态
                        {

          //输出二进制数据给客户端
                            Response.OutputStream.Write(outByte, 0, retval);
                            Response.Flush();
                        }
                        startIndex += bufferSize;
                        if (retval < bufferSize)
                            more = false;
                    }
                    while (more);
                    Response.Close();
                }
                catch (Exception ex)
                {
                     throw New Exception("下载出错!");

}
                finally
                {
                    reader.Close();
                    Response.Close();
                }