【问题标题】:How to refresh image automatically on webpage如何在网页上自动刷新图像
【发布时间】:2017-12-21 01:41:48
【问题描述】:

我正在尝试在网页上获取图像(来自 ipcam)并自动刷新它。我制作了一个后端,它具有读取图像并返回它的功能。这有效,看起来像这样:

[System.Web.Http.HttpGet]
[System.Web.Http.Route("dummymethod3")]
public HttpResponseMessage Get2()
{
    Console.WriteLine("Get image 3");
    ddEngine.sem.WaitOne();

    HttpResponseMessage response = new HttpResponseMessage();

    String filePath = "C:\\Users\\user1\\TestProject\\\\bin\\Debug\\testimage.png";
    response.Content = new StreamContent(new FileStream(filePath, FileMode.Open)); // this file stream will be closed by lower layers of web api for you once the response is completed.
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/png");     


    ddEngine.sem.Release();

    return response;

} 

此函数起作用并返回图像。在客户端,我有一个控制器,它调用获取图像的更新方法。

  activate(){
      setInterval(this.updateStatus.bind(this), 1000);
  }

   updateStatus = function () {
      this.statusService.getImage()
        .then(data => this.message = data);
  }

getImage 方法看起来像这样:

getImage() {
     return this.client.get(baseUrl)
        .then(response => {
           return response.content;
    });
}

html 看起来像这样并正确显示第一张图片。

    <template>
    </script>
   <img id="img" src= "http://localhost:8080/api/status/dummymethod3" />
</template>

在我的自定义 OWIN 中间件中,我添加了一个无缓存值。

    public async override Task Invoke(IOwinContext context)
{
    context.Response.Headers["MachineName"] = Environment.MachineName;
    context.Response.Headers.Add("CACHE-CONTROL", new[] {"NO-CACHE"});

    await Next.Invoke(context);
}

当按下 F5 时,它会重新加载整个页面并获取新图像。我看到调用了 ineval 方法并调用了后端调用。但是图像没有刷新。

有人知道如何刷新图像吗?欢迎提出任何想法!

【问题讨论】:

  • 尝试在图片 url 的末尾添加时间和日期戳,图片可能会因为它被缓存而看起来是一样的。
  • 感谢您的评论,我需要在哪里添加它?由于实际调用“localhost:8080/api/status/dummymethod3?” + datetime 使该方法不再被调用,它找不到它。

标签: javascript html asp.net typescript aurelia


【解决方案1】:

我认为您对尝试解决问题的方式有些混淆。

您正在使用getImage() 方法,但没有对结果做任何事情。因此,即使每秒触发一次 - 它实际上也不会做任何事情。

您可以使用src.bind,然后使用刷新 URL 的函数来重新加载图像,而无需通过 API 调用图像。

您的 HTML;

<img id="img" src.bind="imagePath" />

您的 Javascript;

imagePath = '';

activate(){
    setInterval(this.updateImageSrc.bind(this), 1000);
}

updateImageSrc() {
    let dt = new Date();
    let baseUrl = "http://localhost:8080/api/status/dummymethod3";
    this.imagePath = baseUrl + "?t=" + dt.getTime();
}

这将通过更新虚拟查询参数每秒为您的图像创建一个新 URL。使用src.bind 将确保此 URL 不断更新。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-24
    • 2021-04-08
    • 1970-01-01
    相关资源
    最近更新 更多