ASP.NET에서는 Response.WriteFile() 이라는 함수를 이용해서 파일(바이너리)을 스트림으로 내려보낼 수 있다.

사용 방법은 간단하다.

 

    Response.AddHeader("Content-Disposition", "attachment;filename=\"123.zip\"");
    Response.ContentType = "application/octet-stream";

    Response.WriteFile("C:\\123.zip");

 

즉, URL로 접근이 가능하지 않은 파일을 이와 같은 방법을 통해 동적으로 내려보낼 수 있다.

그런데, 이 파일의 크기가 100MB이상의 대용량인 경우에는 웹 서버에서 에러가 발생하고 다운로드가 안될 수 있다.

그럴 때는 아래 링크를 참조하자.


>> 참조: http://support.microsoft.com/kb/812406


파일 스트림으로 쪼개서 쏘는 방식이다.


위 URL에서 소스코드만 퍼왔다.


System.IO.Stream iStream = null;


// Buffer to read 10K bytes in chunk:

byte[] buffer = new Byte[10000];


// Length of the file:

int length;


// Total bytes to read:

long dataToRead;


// Identify the file to download including its path.

string filepath  = "DownloadFileName";


// Identify the file name.

string  filename  = System.IO.Path.GetFileName(filepath);


try

{

// Open the file.

iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, 

System.IO.FileAccess.Read,System.IO.FileShare.Read);



// Total bytes to read:

dataToRead = iStream.Length;


Response.ContentType = "application/octet-stream";

Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);


// Read the bytes.

  while (dataToRead > 0)

{

// Verify that the client is connected.

if (Response.IsClientConnected) 

{

// Read the data in buffer.

length = iStream.Read(buffer, 0, 10000);


// Write the data to the current output stream.

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


// Flush the data to the HTML output.

Response.Flush();


buffer= new Byte[10000];

dataToRead = dataToRead - length;

}

else

{

//prevent infinite loop if user disconnects

dataToRead = -1;

}

}

}

catch (Exception ex) 

{

// Trap the error, if any.

Response.Write("Error : " + ex.Message);

}

finally

{

if (iStream != null) 

{

//Close the file.

iStream.Close();

}

Response.Close();

}




Posted by 떼르미
,


자바스크립트를 허용해주세요!
Please Enable JavaScript![ Enable JavaScript ]