Shilpa Nagavara
Shilpa Nagavara

Reputation: 1165

Display image using FileStreamResult from ASP.Net MVC

I am developing a captcha control which allows for refresh of the captcha image. I do not have the option of storing the image on the server. I am using ASP.Net MVC for this purpose.

My controller action code:

public FileResult GetCaptchaImage()
{

    // Create a CAPTCHA image using the text stored in the Session object.
    CaptchaImage ci = new CaptchaImage(this.Session
        ["CaptchaImageText"].ToString(), 300, 75);
    // Change the response headers to output a JPEG image.
    MemoryStream stream = new MemoryStream();
    ci.Image.Save(stream, ImageFormat.Png);
    stream.Seek(0, SeekOrigin.Begin);
    return new FileStreamResult(stream, "image/png");
}

The html code to display the image in the razor view

<img id="captchaImage" class="img-responsive" src="@Url.Action("GetCaptchaImage","Home")" />

Now, when I click on the refresh button, this img should get updated. On click of the button, I am calling the same controller action again using an ajax call and it is returning the FileStreamResult.

function RefreshCaptcha() {
$.ajax({
    url: "/Home/GetCaptchaImage"
}).then(function (data) {
    console.log(data);
});

}

Now, using JQuery, how do I set the response content in the image?

Please guide. Thanks very much.

Upvotes: 3

Views: 3235

Answers (1)

Andy T
Andy T

Reputation: 9881

No need to use ajax, simply call the same URL, but pass in a no-cache querystring so it doesn't cache the value and then change the source of the image:

$('#captchaImage').attr('src', '/Home/GetCaptchaImage?nc=' + (new Date).getTime(););

In my example, I'm using epoch time, but you could simply use a random value.

Upvotes: 3

Related Questions