How to download a image file from server to client?


To download a image file from server to client.

1. use Server.MapPath to reteive the file location
2. use System.IO.FileInfo to check the file exists or not
3. Set the ContentType of your response object
4. Append header for "Content-Disposition", "attachment;filename="
5. Use response object's WriteWrite method to write the image
6. Call Response.End()



string filename = Server.MapPath("~/Images/calenda.gif");
System.IO.FileInfo fileInfo = new System.IO.FileInfo(filename);
if (fileInfo.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "inline;attachment; filename=" + fileInfo.Name);
Response.AddHeader("Content-Length", fileInfo.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.Flush();
Response.WriteFile(fileInfo.FullName);
Response.End();
}
else
{
// File Not Found
}


Comments

Author: Saumya Ranjan Ray17 Mar 2010 Member Level: Bronze   Points : 2

I want to provide the filename dynamically. i.e i will not mention the filename say calender.gif as in your code. Instead I will provide the filename through a sql query.
But the location of the file is fixed. say inside "download" folder under the root in Visual studio 2005.

How to do that.
Thanking you

Author: MuhiReks17 Mar 2010 Member Level: Gold   Points : 1


string imgName =calender.gif // code for retreive filename from DB
string filename = Server.MapPath("~/download/" + imgName);



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: