【问题标题】:Link to image database链接到图像数据库
【发布时间】:2011-07-01 23:23:21
【问题描述】:

我有以下页面:

@{
    if (Request["ID"].IsInt())
    {
        var imgID = Request["ID"].AsInt();

        //Data
        var db = Database.Open("AMSDArquiteturaConnectionString");
        var image = db.QuerySingle("select * from Images where [ID] = @0", imgID);

        if (image.MimeType.StartsWith("image"))
        {
            Response.AddHeader("content-disposition", "inline; filename=" + image.Name);
        }
        else
        {
            Response.AddHeader("content-disposition", "attachment; filename=" + image.Name);
        }

        Response.BinaryWrite((byte[])image.File);

    }
}

我正在使用插件来放大图像,我需要使链接指向图像。

<a rel="images" title="MyImage" href="ProjectImage?ID=@img.ID"></a>

问题是当我点击链接时,我看到的只是一个无意义的代码。

如何使此链接指向数据库中的图片?

【问题讨论】:

  • 您能否在问题中包含“无意义的代码”?是错误消息还是只是随机字符?

标签: asp.net razor webmatrix


【解决方案1】:

您需要确定问题在于您使用插件的方式,还是您的 Razor 代码。直接请求页面,硬编码imgID 的值以确保它正常工作。如果您的数据库表和代码基于article from a bloke called Mikesdotnetting,您可以使用WebImage 帮助器对其进行简化:

@{
    WebImage image = null;
    int id = Request["Id"].AsInt();
    var db = Database.Open("FileUploading");
    var sql = "Select * From Files Where FileId = @0";
    var file = db.QuerySingle(sql, id);
    if(file != null){
        image = new WebImage((byte[])file.FileContent);
    }
}   
@if(image != null){
    @image.Write(image.ImageFormat)
}

如果可行,那么插件可能是问题所在。尝试从img 标记请求图像,src 指向生成图像的页面。这是一种奇怪的方法,它使用锚点而不是img 标签来显示图像。

或者它可能是图像本身。 Only some image types are supported by browsers.

【讨论】:

    【解决方案2】:

    您可能需要指定 mime 类型。像这样的:

    Response.ContentType = image.MimeType
    

    “无意义的代码”可能是图像,浏览器只是不知道数据代表图像并以原始格式显示。这段代码应该告诉它它需要知道什么。

    【讨论】:

    • 我也这样做了......同样的事情。放在行上方:Response.BinaryWrite((byte []) image.File);
    • 另一个问题是 SELECT *.您可能希望指定一个字段以确保获得正确的字段。
    • 好的,我同意。我稍后会解决这个问题。但是如何解决当前的问题呢?
    • 如果查询返回的第一个字段是错误的,那可能是您的问题。
    【解决方案3】:

    您为什么要在剃须刀页面中这样做?它应该是控制器中的 Action 方法。像这样。

    public ActionResult Image(int? id) {
        if (id.HasValue) {
            //Data
            var db = Database.Open("AMSDArquiteturaConnectionString");
            var Image = db.QuerySingle("select * from Images where [ID] = @0", id.Value);
    
    
            FileContentResult result = new FileContentResult((byte[])Image.File, Image.MimeType);
    
            if (Image.MimeType.StartsWith("image")) {
                result.FileDownloadName = Image.Name;
            }
            return result;
    
        } else {
            return new HttpNotFoundResult();
        }
    }
    

    我的猜测是,当你以这种方式使用它时,视图引擎会不喜欢它。

    【讨论】:

    • 这个问题被标记为 WebMatrix。 ASP.NET 网页中没有控制器或操作。
    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 2020-02-29
    • 2021-10-16
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2014-11-14
    相关资源
    最近更新 更多