在FileResult Handler中以ajax显示图像(操作)

时间:2019-05-04 10:55:34

标签: c# jquery css asp.net-web-api asp.net-core

我在当前项目中使用Asp.net Core Razor页面...我有一个页面处理程序(操作),用于使用Ajax将图像发送到我的页面...我向我的处理程序发送带有ajax的请求,我的响应是合适的图像到页面,但图像未显示在我的img src标签中!

public IActionResult OnGetDeleteImage(ImageType imageType)
{
    return File(DefaultImage(imageType), "image/png", Guid.NewGuid().ToString());
}

... DefaultImage获取服务器上的图像路径。 和ajax请求:

$.ajax({
    type: 'GET',
    url: deleteImagePath,
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN",
            $('input:hidden[name="__RequestVerificationToken"]').val());
    },

    success: function (data) {
        alert(data);  
            $("#" + id).attr("src",data);

    },
    error: function (err) {
        alert(err);
    }

我的代码返回图像内容,但未在img src中显示。 谢谢。

1 个答案:

答案 0 :(得分:0)

您正在尝试将图像的二进制内容放入需要网址而不是实际数据的src属性中。您可以尝试将该图像格式化为数据url,它应该可以工作。

在此示例中,我假设您的DefaultImage方法返回了PNG文件的路径,但是我不确定。要返回数据uri,它看起来应该像这样:

public IActionResult OnGetDeleteImage(ImageType imageType)
{
    return new ContentResult() {
       Content = "data:image/png;base64," + System.Convert.ToBase64String(System.IO.File.ReadAllBytes(DefaultImage(imageType))),
       ContentType = "text/plain"
    });
}

Data uri仅在IE浏览器中可用于最大32K的图像,并且上面的代码效率不高。

如果可能的话(例如,图像存储在服务器端应用程序的一部分中,可以作为静态文件存储),最好是可以使用C#方法将可公开访问的uri返回到图像文件,然后,当您更新src时,浏览器将从该uri下载文件。看起来像这样:

public IActionResult OnGetDeleteImage(ImageType imageType)
{
    return new ContentResult() {
       Content=GetPublicPathTo(DefaultImage(imageType)), //this should return something like "/img/the_image_to_display.png"
       ContentType="text/plain"
    }
}
相关问题