远程下载文件源码

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

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();



 

  

你可能感兴趣的:(下载文件)