【问题标题】:Show image in ajax from FileResult Handler (Action)从 FileResult 处理程序(操作)以 ajax 显示图像
【发布时间】:2019-09-22 16:59:17
【问题描述】:

我在当前项目中使用 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 中显示。 谢谢。

【问题讨论】:

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


    【解决方案1】:

    您试图将图像的二进制内容放入需要 url 的 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"
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-23
      • 2018-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多