ASP.NET Return image from .aspx link

2020-02-01 01:01发布

Is it possible to output an image (or any file type) to a download link when a user clicks on a link from another ASP.NET page?

I have the file name and byte[].

<a href="getfile.aspx?id=1">Get File</a>

...where getfile returns the file instead of going to the getfile.aspx page.

标签: asp.net
7条回答
在下西门庆
2楼-- · 2020-02-01 01:40

You would want .ashx for that really ;)

public class ImageHandler : IHttpHandler 
{ 
  public bool IsReusable { get { return true; } } 

  public void ProcessRequest(HttpContext ctx) 
  { 
    var myImage = GetImageSomeHow();
    ctx.Response.ContentType = "image/png"; 
    ctx.Response.OutputStream.Write(myImage); 
  } 
}
查看更多
乱世女痞
3楼-- · 2020-02-01 01:48

Yes, this is possible. There are two parts of the Response object you need to set: the Content-Type and the HTTP Header. The MSDN documentation has the details on the response object but the main concept is pretty simple. Just set the code to something like this (for a Word doc).

Response.ContentType="application/ms-word";
Response.AddHeader("content-disposition", "attachment; filename=download.doc");

There is a more complete example here

查看更多
三岁会撩人
4楼-- · 2020-02-01 01:48

ashx...

public class ImageHandler : IHttpHandler
{

    public void ProcessRequest(HttpContext ctx)
    {
       string path = ".....jpg";

                byte[] imgBytes = File.ReadAllBytes(path);
                if (imgBytes.Length > 0)
                {
                    ctx.Response.ContentType = "image/jpeg";
                    ctx.Response.BinaryWrite(imgBytes);
                }
    }

    public bool IsReusable
    {
        get {return false;}
    }
}
查看更多
姐就是有狂的资本
5楼-- · 2020-02-01 01:49

Yeah, you have to clear the response completely and replace it with the image byte data as a string, and you need to make sure to set the response header for content-type according to the type of image

查看更多
太酷不给撩
6楼-- · 2020-02-01 01:56

the codebehind code for getfile.aspx has to have a content-type and the browser will know that it is an image or a unknown file and will let you save it.

In asp.net you can set the ContentType by using the Response object, i.e.

Response.ContentType = "image/GIF"

Here you have a tutorial for dynamically generated image

查看更多
家丑人穷心不美
7楼-- · 2020-02-01 02:01

Here is how I have done this in the past:

Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", string.Format("inline;filename=\"{0}.pdf\"",Guid.NewGuid()));
Response.ContentType = @"application/pdf";
Response.WriteFile(path);
查看更多
登录 后发表回答