ASP.NET - how to create a simple image downloading page in asp.net

Asked By aman on 25-Jul-11 06:38 AM
hi everyone....

i want to create a page with full of images and i want that the user can view and download those images.......
how to do so, please help me with some example.......

thanks and ragards
Aman khan
Ravi S replied to aman on 25-Jul-11 06:40 AM
HI
try this

  1. Create Captcha Image from random numbers and store that number in session variable, we have used Captcha.aspx page for the same.
  2. Use Captcha.aspx as source for the captcha image in Default.aspx page, i.e. for image tag give Captcha.aspx as SRC.
  3. On Submit click simply verify captcha entered by user and captcha in session. 
Our folder structure is very simple, check out following image

http://4.bp.blogspot.com/_QxZLuRPbgeM/TNDvV3W7eLI/AAAAAAAAAUg/z6M1NRk6oC4/s1600/FolderStructure.bmp

To understand the way we have checked captcha, have look on HTML of Default.aspx page (Check out http://www.easy-share.com/1912843853/CaptchaInAsp.zip, for better understanding.)

http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#
  1. <div><table><tbody>  
  2. <tr>         <td>  
  3.   
  4. <img alt="Catptcha Text" src="Captcha.aspx"></td>       </tr>  
  5. <tr>         <td>  
  6.   
  7. <asp:textbox id="txtCaptcha" runat="server"></asp:textbox></td>       </tr>  
  8. <tr>         <td>  
  9.   
  10. <asp:button id="btnSubmit" onclick="btnSubmit_Click" runat="server" text="Submit">          </asp:button></td>       </tr>  
  11. </tbody></table></div>  

Check out the way we have used Captcha.aspx page in image source.

On submit click we simply checks whether Captcha entered in "txtCaptcha" is valid or not, we have following code for submit button clicked.

http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#
  1. protected void btnSubmit_Click(object sender, EventArgs e)  
  2.   {  
  3.     if (Session["Captcha"] != null)  
  4.     {  
  5.       if (txtCaptcha.Text == Session["Captcha"].ToString())  
  6.       {  
  7.         Response.Redirect("RedirectPage.aspx");  
  8.       }  
  9.       else  
  10.       {  
  11.         Response.Write("Please Enter Valid Captcha code");  
  12.         txtCaptcha.Text = "";  
  13.       }  
  14.     }  
  15.     else  
  16.     {  
  17.       Response.Write("Session Expired, please re-enter Captcha.");  
  18.     }  
  19.   }  

Now what remains is the logic for Generate captcha image, we don't have any HTML tags on captcha.aspx, we simply write following code for Binary Image Generation and write it. We have used Random number; but we can have our different logic for the same.

http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html#
  1. protected void Page_Load(object sender, EventArgs e)  
  2.   {  
  3.     Response.ContentType = "text/plain";  
  4.     Random random = new Random(DateTime.Now.Millisecond);  
  5.   
  6.     int number = random.Next(100000);  
  7.   
  8.     Session.Add("Captcha",number.ToString());  
  9.   
  10.     System.Drawing.Bitmap bmpOut = new Bitmap(100, 50);  
  11.   
  12.     Graphics graphics = Graphics.FromImage(bmpOut);  
  13.   
  14.     graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Bilinear;  
  15.   
  16.     graphics.FillRectangle(Brushes.Aquamarine, 0, 0, 100, 50);  
  17.   
  18.     graphics.DrawString(number.ToString(), new Font("TimesNewRoman", 20), new SolidBrush(Color.Coral), 0, 0);  
  19.   
  20.     MemoryStream memorystream = new MemoryStream();  
  21.   
  22.     bmpOut.Save(memorystream, System.Drawing.Imaging.ImageFormat.Png);  
  23.   
  24.     byte[] bmpBytes = memorystream.GetBuffer();  
  25.   
  26.     bmpOut.Dispose();  
  27.   
  28.     memorystream.Close();  
  29.   
  30.     Response.BinaryWrite(bmpBytes);  
  31.   
  32.     Response.End();  
  33.   
  34.   }  
refer http://aspdotnetmatters.blogspot.com/2010/11/generate-captcha-image-in-aspnet-simple.html
Reena Jain replied to aman on 25-Jul-11 06:43 AM
hello,

here is the code to download any file on button click

protected void LnkDownLink_Click(object sender, EventArgs e)
  {
  path = Server.MapPath("filenameorimagename");
  
  FileInfo fileInfo = new FileInfo(path);
  Response.Clear();
  Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name.Replace(" ", "_"));
  Response.AddHeader("Content-Length", fileInfo.Length.ToString());
  Response.ContentType = "application/octet-stream";
  Response.Flush();
  Response.WriteFile((fileInfo.FullName));
  Response.End();
  }

hope this will help you
DL M replied to aman on 25-Jul-11 06:44 AM
you can use Download Images with a Save As Dialog in ASP.NET refer below link will get source code

http://www.how-to-asp.net/download-images-with-save-as-dialog/
Riley K replied to aman on 25-Jul-11 06:49 AM
Create a link to a download page like this:
Download.aspx?Image=whatever.jpg

and then in Download.aspx set the content headers:

Response.ContentType = "image/jpeg";
Response.AddHeader("Content-Disposition", "attachment; filename=whatever.jpg");

The browser will display a save dialog instead of displaying it.

Regards

dipa ahuja replied to aman on 25-Jul-11 06:51 AM
two options you have for that.

1 use the gridview 2. use datalist

i will give you example by using the gridview:

Take a gridview bind it with your images table , assume that you have stored the imageName(nvarchar) and your actula images are inside the folder named images:

Now write this code in aspx:

<asp:TemplateField HeaderText="imageurl">
<ItemTemplate>
<asp:ImageButton ID="ImageButton3" runat="server" 
PostBackUrl='<%# Eval("purl","display.aspx?purl={0}") %>' 
ImageUrl='<%# Bind ("imageurl","images/{0}") %>'
Height="100" Width="100" BorderWidth="2px" />
<br />
<asp:Label ID="lblFileName" runat="server" Text='<%# Eval("imageName") %>'/>
<asp:LinkButton ID="lblFileid" CommandName="Download" runat="server" Text="Download" />
</ItemTemplate>
</asp:TemplateField>

and implement the RowCommand Event:
protected void GridView13_RowCommand(object sender, GridViewCommandEventArgs e)
{
 
  if (e.CommandName == "Download")
  {
    GridViewRow row = (GridViewRow)(((LinkButton)e.CommandSource).NamingContainer);
    string strRequest = ((Label)row.FindControl("lblFileName")).Text;
 
    if (strRequest != "")
    {
      //get absolute path of the file
      // the file is passed like a web address /images/myimage.jpg
      string path = Server.MapPath("~/images/" + strRequest); //get file object as FileInfo  
      System.IO.FileInfo file = new System.IO.FileInfo(path); //-- if the file exists on the server  
 
      if (file.Exists) //set appropriate headers  
      {
        Response.Clear();
        Response.AddHeader("Content-Disposition""attachment; filename=" + file.Name);
        Response.AddHeader("Content-Length", file.Length.ToString());
        Response.ContentType = "application/octet-stream";
 
        // write file to browser
        Response.WriteFile(file.FullName);
        Response.End();
      }
      else
      {
        // if file does not exist
        Response.Write("This file does not exist.");
      }
    }
    else
    {
      //nothing in the URL as HTTP GET
      Response.Write("Please provide a file to download.");
    }
 
  }
}

Jitendra Faye replied to aman on 25-Jul-11 07:21 AM

For this taks you can display image path in gridView, after that use GridView1_SelectedIndexChanging Event of GridView Control().

I have created Sample example based on your requirement, follow this code-

.ASPX Code-

<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"        OnSelectedIndexChanging="GridView1_SelectedIndexChanging">
       <Columns>
         <asp:BoundField DataField="empid" HeaderText="empid" />
         <asp:BoundField DataField="des" HeaderText="des" />
         <asp:BoundField DataField="filename" HeaderText="file" />

         <asp:CommandField  ShowSelectButton="true" />
       </Columns>
     </asp:GridView>


.CS COde

//HERE GETDATA IS A FUCNTION TO GET DATA FROM DATABASE
 
 private void GetData()
    {
      SqlConnection cn = new SqlConnection("CONNECTION STRING");
      cn.Open();
      string strQuery = "Select * from EmpTab";
      SqlDataAdapter da = new SqlDataAdapter(strQuery, cn);
      DataSet ds = new DataSet();
      da.Fill(ds);
 
      GridView1.DataSource = ds.Tables[0];
      GridView1.DataBind(); 
    }

 
protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)

   {
       string filename= GridView1.Rows[e.NewSelectedIndex].Cells[2].Text;

    string path=MapPath("~/soft/" + filename);

    byte []bts=System.IO.File.ReadAllBytes(path);

    Response.Clear();
    Response.ClearHeader();

    Response.AddHeader("Content-Type","Application/octet-stream")
    Response.AddHeader("Content-Length",bts.Length.ToString());
    Response.AddHeader("Content-Disposition","attachment; filename=" + filename);
    Response.BinaryWrite(bts);
    Response.Flush();
    Response.End();

    }

USE THIS CODE AND LET ME KNOW.