如何使用C#中的按钮单击下载图像?

时间:2013-02-15 16:51:02

标签: c# asp.net download

有没有办法下载用户上传的图片?我有以下内容:首先,用户点击马赛克中的图像进行详细查看;然后在asp:image标签中生成图像,在该步骤中,他们应该通过单击按钮下载它。我遇到的问题是图像是在asp:image标签中生成的,而不是具有名称的实际图像本身。我必须下载的代码只获取存储在文件夹中的图像。以下是代码:

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.");
    } 
}

以下是预览图片的代码:

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

3 个答案:

答案 0 :(得分:0)

使用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();
}

答案 1 :(得分:0)

使用WebClient

using System;
using System.Net;

// ...
    WebClient webClient = new WebClient();
    webClient.DownloadFile("http://orig14.deviantart.net/d7a5/f/2016/123/0/9/judy_and_nick_by_kuvshinov_ilya-da15pnt.jpg", "MyFile.jpg");

答案 2 :(得分:0)

你可以试试这个:

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();
}