【问题标题】:Continually request image until found不断请求图像直到找到
【发布时间】:2013-03-05 17:41:25
【问题描述】:

我正在开发一个允许异步上传图像的界面,并且该过程按预期工作。该进程将图像提交给后端进程,该进程管理将图像调整为不同大小并将它们存储在云中。我生成 url,最终图像被上传(通常在 10 秒内)到适当的调整大小。

图片上传后,界面中没有显示该图片的缩略图,很明显,因为它还没有调整大小。

我想做的是,在创建图像并提交到后端服务以调整大小之后,客户端上的一个进程附加到每个上传尝试(我正在考虑使用 setinterval )来继续寻找该图像,直到它解决,一旦解决,使用该图像更新缩略图占位符。

一旦图像确实按请求解析,我如何提供该图像以更新界面?

【问题讨论】:

  • 一个简单的解决方案可能是使用“setTimeout”每隔 x 秒检查一次图像,直到它显示出来。

标签: javascript ajax http interface upload


【解决方案1】:

Pure JavaScript 使用 setTimeoutonerroronload 事件:

var img,
    attempt = 2;

checkForImage("https://ssl.gstatic.com/apps/cpanel/resources/img/apps_logo_new.png3",
             document.getElementById("message"));

function checkForImage(location, loadto) {    
    img = document.createElement("img")

    img.onerror = function () {
        setTimeout(function() {
            checkForImage(location, loadto);
            loadto.innerText = "Finding Picture... Attempt: " + attempt++;
        }, 5000); 
    }

    img.src = location;

    img.onload = function () {
        loadto.innerHTML = "<img src='" + location + "' />";
    }
}

删除image链接末尾的3将显示一个成功的示例。

【讨论】:

    【解决方案2】:

    根据您确定那里没有图像的方式(404 错误,某种 API 返回带有 URL 的 JSON?),您可以使用 jQuery.ajax() 根据 HTTP 状态代码很容易地采取行动。

    function waitforimage(imageURL) {
        $.ajax(url, { 
            statusCode: {
                // on 404 wait and do it again later
                404: function() {
                    setTimeout(function(){
                        waitforimage(imageURL);
                    }, 3000);
                },
                // on success, load the image
                200: function() {
                    loadimage(imageURL);
                }
            }
        });
    }
    
    function loadimage(imageURL) {
         $('#myimageID').attr('src', imageURL);
    }
    

    当然,不使用 jQuery 也可以做到,但要让它发挥作用需要更多的摆弄。

    【讨论】:

    • 成功不应该是200吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2019-05-15
    • 1970-01-01
    • 1970-01-01
    • 2021-07-23
    • 1970-01-01
    相关资源
    最近更新 更多