开发者

ASP.NET Return image from .aspx link

开发者 https://www.devze.com 2022-12-20 12:47 出处:网络
Is it possible to output an image (or any file type) to a download l开发者_JS百科ink when a user clicks on a link from another ASP.NET page?

Is it possible to output an image (or any file type) to a download l开发者_JS百科ink 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.


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


How to Create Text Image on the fly with ASP.NET

Something like this:

string Path = Server.MapPath(Request.ApplicationPath + "\image.jpg");
Bitmap bmp = CreateThumbnail(Path,Size,Size);
Response.ContentType = "image/jpeg";
bmp.Save(Response.OutputStream,System.Drawing.Imaging.ImageFormat.Jpeg);
bmp.Dispose();


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


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


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


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


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;}
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消