Jacman
Jacman

Reputation: 1592

How to download an image with the button click in C#?

Is there a way to download an image that was uploaded by the user? I have the following: First, the user click an image from a mosaic to view it in detail; then the image is generated in a asp:image tag, at that step they are supposed to download it with a button click. The problem I have is that the image is generated in a asp:image tag and is not the actual image itself with a name. The code I have to download only gets the image stored in a folder. Below is the code:

protected void btnDownload_Click(object sender, EventArgs e)
{
    string path = @"C:\inetpub\wwwroot\PSCSearchEngine\MemberPages\Images\live.jpg";        
    System.IO.FileInfo file = new System.IO.FileInfo(path);
    if (file.Exists)
    {
        Response.Clear();
        Response.ContentType = MimeType(Path.GetExtension(path));
        Response.AddHeader("Content-Disposition", 
            string.Format("attachment; filename = {0}",
            System.IO.Path.GetFileName(path)));
        Response.AddHeader("Content-Length", file.Length.ToString("F0"));
        Response.TransmitFile(path);
        Response.End();
    }
    else
    {
        Response.Write("This file does not exist.");
    } 
}

Below is the code that previews the image:

@"~/MemberPages/UpdatePhoto.aspx?SiteKey=" + foo.Site_ID 
    + "&TimeStamp=" + foo.timestamp[n1 - 1];

Upvotes: 0

Views: 15261

Answers (2)

G J
G J

Reputation: 527

You may try this:

using (var client = new System.Net.WebClient())
{
    var _imagebytes = client.DownloadData(string.Format(@"~/MemberPages/UpdatePhoto.aspx?SiteKey={0}&TimeStamp={1}", foo.Site_ID, foo.timestamp[n1 - 1]));
    Response.Clear();
    Response.ContentType = "image/jpg";
    Response.AddHeader("Content-Disposition", string.Format("attachment; filename = {0}", "MyImage.jpg"));
    Response.AddHeader("Content-Length", _imagebytes.Length.ToString("F0"));
    Response.OutputStream.Write(_imagebytes, 0, _imagebytes.Length);
    Response.End();
}

Upvotes: 1

ss4sp developers
ss4sp developers

Reputation: 11

Code for download an image file with the button click in C#

protected void btnDownload_Click(object sender, EventArgs e)
{
    string filename=MapPath("birds.jpg");
    Response.ContentType = "image/JPEG";
    Response.AddHeader("Content-Disposition", "attachment; filename=" + filename+ "");

    Response.TransmitFile(filename);
    Response.End();
}

Upvotes: 1

Related Questions