Tuesday, November 8, 2011

How to write image downloader using IHttpHandler in asp.net

First of all, create the Generic Handler(.ashx) as below.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
public class Downloader : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        try
        {
            HttpResponse Response = context.Response;
            HttpRequest Request = context.Request;

            string fileName = "IMG.jpg";
            string fullPath = @"G:\" + fileName;  //here is your image path.

            if (!string.IsNullOrEmpty(fileName))
            {
                System.IO.FileInfo finfo = new System.IO.FileInfo(fullPath);
                System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
                int byteLen = (int)fs.Length;
                byte[] file = new byte[byteLen];
                fs.Read(file, 0, byteLen);
                string name = finfo.Name;
                string size = byteLen.ToString();
                Response.Clear();
                Response.ContentType = "application/octet-stream";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + name);
                Response.AddHeader("Content-Length", size);
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.BinaryWrite(file);
                fs.Flush();
                fs.Close();
                HttpContext.Current.ApplicationInstance.CompleteRequest();

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Put the following control to <form> tag.
<asp:HyperLink ID="HyperLink1" runat="server" NavigateUrl="~/Downloader.ashx">Download Image</asp:HyperLink>

That's it. Whenever you click the link, it will show the download dialog box.
Enjoy!

No comments:

Post a Comment