상세 컨텐츠

본문 제목

대용량 데이타 다운로드

Web/ASP.NET

by 탑~! 2014. 1. 3. 08:39

본문

Response.WriteFile()은 일반적으로 많이 사용된다. 하지만 맹점이 하나 존재하는데 이는 최초 파일을 읽어들여 모두 메모리 상에 로드 시킨다. 이때 문제가 발생하게 되는데 대용량의 데이터인 경우에는 메모리의 한계때문에 서버가 다운되는 현상까지 나타나게 되는 것이다.

ASP.NET 1.1 : 대용량 데이터 다운시 서버 다운까지 발생할 수 있는 위험한 코드(하지만 일반적인 방법)

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "Application/Octet-Stream";
FileInfo objFileInfo = new FileInfo(path);
Response.AppendHeader("Content-Disposition", "Attachment; Filename="
           + Server.UrlEncode(objFileInfo.FullName).Replace("+", "%20"));
Response.AppendHeader("Content-Length", objFileInfo.Length.ToString());
Response.WriteFile(path);
Response.Flush();
Response.End();


ASP.NET 1.1 개선 : 메모리의 개선이 상당히 많이 이루어 지나 CPU의 자원을 많이 소비

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "Application/Octet-Stream";
FileInfo objFileInfo = new FileInfo(path);
Response.AppendHeader("Content-Disposition", "Attachment; Filename="
  + Server.UrlEncode(objFileInfo.FullName).Replace("+", "%20"));
Response.AppendHeader("Content-Length", objFileInfo.Length.ToString());
int BUFFER_SIZE = 1024;
using (FileStream objFileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))
{
  byte[] buffer = new Byte[BUFFER_SIZE];
  long remainder = objFileStream.Length;
  while (remainder > 0)
  {
       if (Response.IsClientConnected)
       {
           int readLength = objFileStream.Read(buffer, 0, BUFFER_SIZE);
           Response.OutputStream.Write(buffer, 0, readLength);
           Response.Flush();
           buffer = new Byte[BUFFER_SIZE];
           remainder = remainder - readLength;
       }
       else
           remainder = -1;
  }
}
Response.Flush();
Response.End();


ASP.NET 2.0 : CPU와 메모리의 자원을 가장 효율적으로 사용할 수 있음

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "Application/Octet-Stream";
FileInfo objFileInfo = new FileInfo(path);
Response.AppendHeader("Content-Disposition", "Attachment; Filename="
  + Server.UrlEncode(objFileInfo.FullName).Replace("+", "%20"));
Response.AppendHeader("Content-Length", objFileInfo.Length.ToString());
Response.TransmitFile(path);
Response.Flush();
Response.End();




출처 : http://kyeongkyun.tistory.com/21

관련글 더보기