17 December, 2009

Stream a file to a client using a postback

It is sometimes desired to allow a client to download a file from your website, and at the same time log this action in a database. Creating this functionality using a direct hyperlink does not allow for the desired logging; but if the file is exposed behind a postback button (server-side), the file can be streamed to the clients browser, and the action can be logged as desired as it is all taking place server-side.

The below class [ResponseStreamer] can be used to stream a file to a client by supplying it with a FileInfo object. The client will experience this as a “Save-As” dialog.

public static class ResponseStreamer
{
/// <summary>
///
Writes the file to the clients browser.
/// </summary>
/// <param name="file">
The file.</param>
public static void StreamFileToClient(FileInfo file)
{
HttpResponse resp = HttpContext.Current.Response;
resp.Clear();
resp.AddHeader("Content-Disposition","attachment; filename={0}", file.Name);
resp.AddHeader("Content-length", file.Length.ToString());
resp.ContentType = "application/octet-stream";
resp.WriteFile(file.FullName);
resp.End();
}
}

static class HttpResponseExtension
{
public static void AddHeader(this HttpResponse resp, string name, string format, params object[] args)
{
resp.AddHeader(name, string.Format(format, args));
}
}

InRiver: Not loading your extensions?

(You really need to in the loop to appreciate the issue this post addresses). Man, I've been fighting this problem for hours before I ...