0

In my website that I am currently working on, I store some images in a folder in the same directory as my .aspx files in the project file. What method can I use to write a code so that when someone clicks an asp:Button, the browser downloads the image (with a given url) for them.

Here is a code example of what it would look like.

Protected Sub button_img_Click(sender As Object, e As EventArgs) Handles button_img.Click
    MagicalFunctionDownloadImage("image.jpeg")
End Sub

Hope that made sense! Thanks in advance!

user2930100
  • 346
  • 4
  • 10
thephysicsguy
  • 403
  • 1
  • 4
  • 15
  • You need to write the file to the response. Here is an example:[http://stackoverflow.com/questions/13779139/writing-memorystream-to-response-object][1] [1]: http://stackoverflow.com/questions/13779139/writing-memorystream-to-response-object – user2930100 Mar 30 '14 at 23:15

1 Answers1

0

The asp:button will really be just a hyperlink, and you'll set a url item that corresponds to your image. It will point to a handler (*.ashx file) that you build, instead of a page (*.aspx file). The handler works much like a page, but without some of the cruft you won't use, and it will allow to set a few specific headers. You then use Response.BinaryWrite() to send the file data to the browser:

Response.Clear()
Response.AddHeader("content-disposition", "attachment;filename=<filename here>")
Response.ContentType = "<content/type here>"
Response.BinaryWrite(<path to file or byte array goes here>)
Response.Flush()
Response.End()
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794
  • Thanks very much for the solution! Can you possibly suggest any implementation as to how to get the size of the image in bytes to create the byte array? I tried 'Dim Buffer(Image.FromFile("image.jpg").Length) As Byte' but it gave me an error saying FromFile is not a member of Sytem.ExceptionControls.Image (something like that)! – thephysicsguy Mar 31 '14 at 13:47