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));
}
}
1 comment:
HP2-H91 dumps - Pass your HP HP2-H91 certification exam with Marks4sure valid HP2-H91 practice test questions answers dumps with 100% passing guarantee.
Post a comment