使用C#在ASP.net中显示数据库中的图像

Mix*_*oid 3 database asp.net image

我知道很多次都会问过这种问题.但我没有成功在页面上显示我的数据库中的图像.

我尝试了以下方法.

    protected void Page_Load(object sender, EventArgs e)
    {
        //Get the picture id by url
        //Query here
        byte[] picture = queryoutput;
        Response.ContentType = "image/jpeg";
        Response.BinaryWrite(picture);
    }
Run Code Online (Sandbox Code Playgroud)

链接获取图像.

<asp:Image runat="server" ImageUrl="~/givememypicture.aspx?pic=3" ID="testimage" />
Run Code Online (Sandbox Code Playgroud)

<asp:Image />标签位于之间<asp:Content >标签.

当我运行此代码并检入firebug时,它只是声明"无法加载fiven URL".我也尝试将该Respone.Con...(picture);部分放入一个公共方法,并使用给定的字节var调用该方法.

我是asp.net的新手,但我在c#方面有一些经验.我开始真的不喜欢asp.net ...我已经在这个问题上苦苦挣扎了大约20个小时并尝试了很多选择,但没有一个工作.

如果我可以通过同一页面的代码文件填写图片,那将是最好的.调用另一个页面来加载图像对我来说似乎很不合逻辑.

有人可以告诉我这里我做错了什么吗?

解决方案:从处理图像响应的页面上的页面指令中删除了母版页引用.除了aspx文件中的@page指令本身之外,还删除了其他所有内容.

sta*_*k72 6

尝试使用一个处理程序文件(.ashx)把你的page_load中的代码放在那个谎言中

public void ProcessRequest (HttpContext context) {
    //Get the picture id by url
        //Query here
        byte[] picture = queryoutput;
        Response.ContentType = "images/jpeg";
        Response.BinaryWrite(picture);
    }

    public bool IsReusable {
    get {
        return false;
    }
    }
Run Code Online (Sandbox Code Playgroud)

然后调用处理程序文件并从中传递正确的查询字符串项

这应该工作


Dav*_*vid 5

您的路径引用中存在错误...

ImageUrl="/~givememypicture.aspx?pic=3"
Run Code Online (Sandbox Code Playgroud)

应该:

ImageUrl="~/givememypicture.aspx?pic=3"
Run Code Online (Sandbox Code Playgroud)

~是"应用程序根"的简写,需要后跟斜杠表示它是一个目录.可以认为它类似于其他路径速记符号,例如....