Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 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);
    }

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
229 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.

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 only works on images up to 32K in IE browsers, and the code above isn't very efficient.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...