如何在asp:Image对象中使用.ashx处理程序?

3

我有一个ashx处理程序:

<%@ WebHandler Language="C#" Class="Thumbnail" %>

using System;
using System.Web;

public class Thumbnail : IHttpHandler
{

    public void ProcessRequest(HttpContext context)
    {
        string imagePath = context.Request.QueryString["image"];

        // split the string on periods and read the last element, this is to ensure we have
        // the right ContentType if the file is named something like "image1.jpg.png"
        string[] imageArray = imagePath.Split('.');

        if (imageArray.Length <= 1)
        {
            throw new HttpException(404, "Invalid photo name.");
        }
        else
        {
            context.Response.ContentType = "image/" + imageArray[imageArray.Length - 1];
            context.Response.Write(imagePath);
        }
    }

    public bool IsReusable
    {
        get { return true; }
    }
}

目前,此处理程序只是获取一张图片并返回它。在我的aspx页面中,我有这行代码:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

而它背后的C#代码如下:

Image1.ImageUrl = "Thumbnail.ashx?image=../Files/random guid string/test.jpg";

当我浏览网页时,图片不显示,而HTML代码则完全显示我所输入的内容。
<img class="thumbnail" src="Thumbnail.ashx?image=../Files%5Crandom guid string%5Cimages%5Ctest.jpg" style="border-width:0px;" />

有人能告诉我为什么这不起作用吗?不幸的是,我昨天才开始使用ASP.NET,对它的工作原理一无所知,请尽可能简单地解释,谢谢。

3个回答

5
你正在输出图像的路径,而不是实际的图像内容。请使用
context.Response.WriteFile(context.Server.MapPath(imagePath));

请使用方法来代替。

确保将路径限制在安全位置。否则,您可能会引入安全漏洞,因为用户可以查看服务器上任何文件的内容。


实际上,我只需要路径,因为我想设置img src。稍后我打算让HttpHandler生成缩略图,然后返回其路径。 - Daniel
那不是HTTP处理程序的作用。浏览器只将处理程序视为图像文件,它无法更改页面的原始HTML响应。 - Mehrdad Afshari

2

这段代码可以帮助从指定路径查看文件名对应的图片。
例如:http://onlineshoping.somee.com/Fimageview.ashx?FImageName=FrozenToront.Jpg

您可以在ASPX HTML body中使用.ashx。

示例:

<image src="/Timageview.ashx?TImageName=FrozenToront.Jpg"
                                      width="100" height="75" border="1"/>


    <%@
        WebHandler Language="C#"
        Class="Fimageview"
    %>

    /// <summary>
    /// Created By Rajib Chowdhury Mob. 01766-306306; Web: http://www.rajibs.tk
    /// Email: mysuccessstairs@hotmail.com
    /// FB: https://www.facebook.com/fencefunny
    /// 
    /// Complete This Page Coding On Fabruary 12, 2014
    /// Programing C# By Visual Studio 2013 For Web
    /// Dot Net Version 4.5
    /// Database Virsion MSSQL Server 2005
    /// </summary>

    using System;
    using System.IO;
    using System.Web;

public class Fimageview : IHttpHandler {

    public void ProcessRequest(HttpContext context)
    {

        HttpResponse r = context.Response;
        r.ContentType = "image/png";
        string file = context.Request.QueryString["FImageName"];
        if (string.IsNullOrEmpty(file))
        {
            context.Response.Redirect("~/default");//If RequestQueryString Null Or Empty
        }
        try
        {
            if (file == "")
            {
                context.Response.Redirect("~/Error/PageNotFound");
            }
            else
            {
                r.WriteFile("/Catalog/Images/" + file); //Image Path If File Name Found
            }
        }
        catch (Exception)
        {
            context.Response.ContentType = "image/png";
            r.WriteFile("/yourImagePath/NoImage.png");//Image Path If File Name Not Found
        }
    }
    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

1
你的例子非常好,是我见过的最佳解决方案。 - Istiyak Amin

0

我是原帖发布者,最终我找到了问题所在。我所需要做的就是更改:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" />

至:

<asp:Image ID="Image1" runat="server" CssClass="thumbnail" imageurl='<%# "~/Thumbnail.ashx?image=" + Utilities.ToURLEncoding("~\\Files" + DataBinder.Eval(Container.DataItem, "file_path")) %>' />

需要将标点符号更改为其HTML等效形式,因此反斜杠变成%5C等等,否则它不起作用。

哦,我忘了提到,这在DataList中。在DataList之外使用Image1.ImageUrl = "Thumbnail.ashx?image=blahblah";完全正常,奇怪的是。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接