Can't render an img by setting its src to returned MVC action response data from jQuery request

I have this jQuery code inside a view:

$(document).ready(function () {
    $(document).on('input', '#usernameTextBox', function () {
        $.get(
            '@Url.Action("GetCAPTCHAImage")',
            { username: $("#usernameTextBox").val() },
            function (data) {
                $("#captchaImage").height(50);
                $("#captchaImage").width(400);
                $("#captchaImage").attr("src", "data:image/png, " + data);
            }
        );
    });
})

The action it calls is this (it works, I can browse to this action in my web browser to view the generated image and Google Chrome displays it just fine without any complaints):

[HttpGet]
public async Task<ActionResult> GetCAPTCHAImage(string username)
{
    try
    {
        return File(GenerateCaptcha(username, 40, 50), "image/png");
    }
    catch
    {
        return File(new byte[] { 0 }, "image/png");
    }
}

The jQuery logic grabs an image from my controller's action and then tries to set the source of the following <img/> element to it:

<img id="captchaImage" />

The problem is that it won't render the image, but I see the data gets returned and everything:

What is the problem?

Answers


I needed to return a base 64 string:

[HttpGet]
public async Task<string> GetCAPTCHAImage(string username)
{
    try
    {
        return Convert.ToBase64String(GenerateCaptcha(username, 40, 50));
    }
    catch
    {
        return String.Empty;
    }
}

Also, this was the wrong format as the image was JFIF or jpeg based (also note the base64):

$("#captchaImage").attr("src", "data:image/jpeg;base64," + data);

Need Your Help

PyQt5 connection doesn't work: item cannot be converted to PyQt5.QtCore.QObject in this context

python qt pyqt signals-slots pyqt5

I am trying to connect a signal from a created object and am getting an error. Here is a simplified version of my code:

Android: How much overhead is generated by running an empty method?

java android performance overhead

I have created a class to handle my debug outputs so that I don't need to strip out all my log outputs before release.