jquery - 使用来自 ASP.Net MVC 的 FileStreamResult 显示图像

标签 jquery html asp.net-mvc image stream

我正在开发一个允许刷新验证码图像的验证码控件。我没有将图像存储在服务器上的选项。为此,我正在使用 ASP.Net MVC。

我的 Controller 操作代码:

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

在 Razor View 中显示图像的 html 代码

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

现在,当我点击刷新按钮时,这个 img 应该会更新。单击按钮时,我使用 ajax 调用再次调用相同的 Controller 操作,它返回 FileStreamResult。

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

现在,使用JQuery,如何在图片中设置响应内容?

请指导。非常感谢。

最佳答案

无需使用 ajax,只需调用相同的 URL,但传入一个无缓存查询字符串,这样它就不会缓存该值,然后更改图像的来源:

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

在我的示例中,我使用的是纪元时间,但您可以简单地使用随机值。

关于jquery - 使用来自 ASP.Net MVC 的 FileStreamResult 显示图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39900275/

相关文章:

javascript - jQuery 代码可以在 JSFiddle 上运行,但不能在我的 Web 应用程序中运行

javascript - 使用 angularjs 和 IFrame 进行页面滚动

javascript - 使用 jQuery 创建 Accordion ,但得到 "$ is not defined"

php - jQuery AJAX 调用两次

jquery - 从 aspx.cs 调用 jQuery 函数

html - h1 在 firefox 的网格布局中具有空大小

javascript - 本地跨源数据错误

c# - 如何创建一个只读 token 来验证某些值?

asp.net-mvc - 如何在 ASP.NET MVC 中显示外键字段的显示名称

ASP.NET MVC : Can I change my mind about having a strongly typed view?