Sunday, February 22, 2009

Tricky Simple File Download Proxy Handler

Today I wanna play a bit with Streams and specially with Response.OutputStream. So I decided to make a Simple File Download Proxy Handler in order to Download Files through an HttpHandler which download Files from Remote Site.

It’s Tricky, and may not be very useful :)

Here is the Code

public class FileProxyHandlerBase : HttpHandlerBase
{
#region Private Properties

private String RemoteUrl { get; set; }
private Uri RemoteUri { get; set; }
private String FileName { get; set; }

#endregion

protected override void Process()
{
if (!String.IsNullOrEmpty(Request.QueryString["url"]))
{
RemoteUrl = Request.QueryString["url"];
}

Uri uri;
if (!Uri.TryCreate(RemoteUrl, UriKind.Absolute, out uri))
{
Response.Write("Unable to Process File");
Response.End();
return;
}
RemoteUri = uri;

if (RemoteUri.Scheme == Uri.UriSchemeFtp)
{
Response.Write("Unable to Process File");
Response.End();
return;
}

int index = RemoteUrl.LastIndexOf("/") + 1;
FileName = RemoteUrl.Substring(index, RemoteUrl.Length - index);

HttpWebRequest _webRequest = WebRequest.Create(RemoteUri) as HttpWebRequest;
Stream ResponseStream = _webRequest.GetResponse().GetResponseStream();

Response.ClearContent();
Response.ContentType = "text/plain";
Response.AddHeader("Content-Disposition", "attachment; filename=" + FileName);

using (BinaryWriter bw = new BinaryWriter(Response.OutputStream))
{
byte[] buffer = new byte[1];
while (ResponseStream.Read(buffer, 0, 1) > 0)
{
bw.Write(buffer);
}
}
Response.End();
}
}

You should use it like that : http://mysite.com/MyHandler.ashx?url=http://www.myRemoteSite.com/MyFile.zip


Source : http://blog.sb2.fr/post/2008/12/21/Tricky-Simple-File-Download-Proxy-Handler.aspx

No comments:

Post a Comment