Monday, June 30, 2008

Retrieving a file that is stored in a database as an image.

1. Create a "File Server" as an HttpHandler
-Within the web.config, set up a page (filemanager.aspx below) that will handle http requests.

<system.web>
  <httpHandlers>
    <add verb="*" path="filemanager.aspx" type="Project.FileManagerHttpHandler, DLLName"/>
  </httpHandlers>
</system.web>

2. Within the html page, create a hyperlink to the http handler
http post to server: <a href="http://url/fileserver.aspx?uniqueIdentifier">click here</a>

3. Create the class that will handle the http request

public class FileServerHttpHandler : IHttpHandler, IRequiresSessionState
{
  // Override the ProcessRequest method.
  public void ProcessRequest(HttpContext context)
  {
    try
    {
      Guid token = new Guid(context.Request.QueryString.ToString());

      BinaryWriter bw;
      context.Response.Clear();
      using (SqlDataReader dr = SqlHelper.ExecuteReader(DBHelper.ConnectionString, "FileGetByFileToken", token))
        {
        if (dr != null)
        {
          if (dr.Read())
          {
context.Response.ContentType = dr["filetype"].ToString();
            byte[] o = (byte[]) dr["filedata"];
              bw = new BinaryWriter(context.Response.OutputStream);
              bw.Write(o);
            }
            dr.Close();
          }
        }
      }
    catch (Exception)
    {
    }
  }

  // Override the IsReusable property.
  public bool IsReusable
  {
    get { return true; }
  }

No comments: