我正在开发一个允许以异步方式上传图像的界面,并且该过程按预期工作。该过程将图像提交到后端进程,该后端进程管理将图像调整为不同大小并将其存储在云上。我生成了网址,最终将图片上传(通常在不到10秒钟内)到适当的大小调整。
上传图片后,显然没有在界面中显示该图片的缩图,因为它尚未调整大小。
我想做的是,在创建映像之后,并提交到后端服务以进行调整大小,客户端上的进程附加到每次上载尝试(我正在考虑使用setinterval)继续寻找该图像,直到它结算,一旦它解决,用该图像更新缩略图占位符。
图像确实按要求解析后,如何提供图像以更新界面?
答案 0 :(得分:0)
根据你如何确定那里没有图像(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的情况下做到这一点,但是会有更多的摆弄它以使其正常工作。
答案 1 :(得分:0)
Pure JavaScript使用setTimeout
,onerror
和onload
事件:
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 + "' />";
}
}
删除3
链接末尾的image
会显示一个成功的示例。