(转)远程下载文件源码

原文地址:

http://www.cnblogs.com/youngerliu/archive/2012/03/07/2384195.html

 






/**********
小文件************/

Response.ClearContent();

Response.ClearHeaders();

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

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

System.Net.HttpWebRequest request =
(System.Net.HttpWebRequest)System.Net.WebRequest.Create(
"http://dotnet.aspx.cc/Images/logoSite.gif");

System.Net.HttpWebResponse response =
(System.Net.HttpWebResponse)request.GetResponse();

Stream stream =
response.GetResponseStream();

byte[] bytes =
new byte[response.ContentLength];

stream.Read(bytes, 0,
Convert.ToInt32(response.ContentLength));

HttpContext.Current.Response.BinaryWrite(bytes);

Response.Flush();

Response.Close();


/********** 大文件************/

HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(
"http://www.xljsf.com//admin/UploadFile/20076222121122.wma");

request.Timeout = 150000;


HttpWebResponse response =
(HttpWebResponse)request.GetResponse();

Stream stream
= response.GetResponseStream();


Response.Clear();

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

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


int
buffer = 1024;

while (true)

{

  byte[] bytes = new
byte[buffer];

  int alreadyRead = stream.Read(bytes, 0, buffer);

  if (alreadyRead == 0) break;

  if (alreadyRead == buffer)

    Response.BinaryWrite(bytes);

  else

  {

    byte[] lastBytes = new byte[alreadyRead];

    for (int i = 0; i < alreadyRead; i++)

      lastBytes[i] =
bytes[i];

    Response.BinaryWrite(lastBytes);

  }

}

Response.End();

  

posted on 2012-05-23 00:00  黑子范  阅读(244)  评论(0编辑  收藏  举报

导航