在FileResult Handler中以ajax显示图像(操作) [英] Show image in ajax from FileResult Handler (Action)

查看:40
本文介绍了在FileResult Handler中以ajax显示图像(操作)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

i using Asp.net Core Razor Page for my Current Project ... I have a Page-Handler (Action) for send image to my page with Ajax ... I send request with ajax to my handler and my response is Suitable image to page but image dont show in my img src tag !

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

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

... DefaultImage get image path on server . and ajax request :

$.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中显示.谢谢.

my code return image content but dont show that in img src . thanks.

推荐答案

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

You are trying to place the binary contents of the image into the src attribute which expects a url, not the actual data. You can try to format that image as data url and it should work.

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

I am assuming your DefaultImage method returns a path to a PNG file in this example, but I can't tell that for sure. To return a data uri, it would look something like this:

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的图像,并且上面的代码效率不高.

Data uri only works on images up to 32K in IE browsers, and the code above isn't very efficient.

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

If possible (e.g. the image is stored in part of your server-side app that can be served up as static files), it would be best if you could return a publicly accessible uri to the image file on the C# method, and then the browser would download the file from that uri when you updated src. That would look like this:

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"
    }
}

这篇关于在FileResult Handler中以ajax显示图像(操作)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆