【发布时间】:2010-02-12 16:17:28
【问题描述】:
当用户单击另一个 ASP.NET 页面的链接时,是否可以将图像(或任何文件类型)输出到下载链接?
我有文件名和字节[]。
<a href="getfile.aspx?id=1">Get File</a>
...getfile 返回文件而不是转到 getfile.aspx 页面。
【问题讨论】:
标签: asp.net
当用户单击另一个 ASP.NET 页面的链接时,是否可以将图像(或任何文件类型)输出到下载链接?
我有文件名和字节[]。
<a href="getfile.aspx?id=1">Get File</a>
...getfile 返回文件而不是转到 getfile.aspx 页面。
【问题讨论】:
标签: asp.net
你真的会想要.ashx for that ;)
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
类似这样的:
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();
【讨论】:
这是我过去的做法:
Response.Clear();
Response.Buffer = true;
Response.AddHeader("Content-Disposition", string.Format("inline;filename=\"{0}.pdf\"",Guid.NewGuid()));
Response.ContentType = @"application/pdf";
Response.WriteFile(path);
【讨论】:
是的,你要彻底清除response并用图片字节数据作为字符串替换它,并且你需要确保根据image的类型为content-type设置response header
【讨论】:
是的,这是可能的。您需要设置 Response 对象的两个部分:Content-Type 和 HTTP Header。 MSDN documentation 包含有关响应对象的详细信息,但主要概念非常简单。只需将代码设置为类似这样(对于 Word 文档)。
Response.ContentType="application/ms-word";
Response.AddHeader("content-disposition", "attachment; filename=download.doc");
还有一个更完整的例子here
【讨论】:
getfile.aspx 的代码隐藏代码必须有一个content-type,浏览器会知道它是图像或未知文件并让您保存它。
在 asp.net 中,您可以使用Response 对象设置ContentType,即
Response.ContentType = "image/GIF"
Here你有动态生成图片的教程
【讨论】:
灰...
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;}
}
}
【讨论】: