我正在使用以下代码从我的服务器获取图片:
<a href="#">
<img src="<%
if(user.getImageURL()!=null){
out.print(user.getImageURL);
}else{
out.print("images/no-profile-pic-small.jpg");
}%>" />
</a>
上面的代码处理imageURL为null时的情况,但是当imageURL返回正确的URL但是在服务器上找不到该图像时,如何处理这种情况,即404 Not Found?
编辑:图片位于其他服务器上。
答案 0 :(得分:2)
目前,您没有在JSP中检查路径,只是将路径放在HTML中(如果存在)。这意味着在HTTP请求通过映像之前,您不知道路径是否存在。你有两个主要选择:
在包含JSP代码之前检查该路径中是否有文件,否则回退到占位符:
<%
String userImagePath = user.getImageURL();
File userImage= new File(userImagePath);
if(!userImage.exists()){
userImagePath = "fallBackImagePath.png";
}
%>
<img src="<%= userImagePath %>"/>
或者让HTML处理非显示图像,例如:
<img src="non-existent.png" class="fallBackBackground"/>
<style>
.fallBackBackground {
background: url(./placeholderImage.png);
}
</style>
这可能会导致您提供不需要的后备图像,而且它依赖于相同大小的图像。
答案 1 :(得分:0)
我使用jquery和 onerror
属性解决了这个问题:
我的服务器端代码现在是:
<a href="#">
<img src="<%
if(user.getImageURL()!=null){
out.print(user.getImageURL);
}else{
out.print("images/no-profile-pic-small.jpg");
}%>" onerror="profilePicNotFound(this);"
/>
</a>
一个小的jquery函数:
function profilePicNotFound(image){
image.src='images/no-profile-pic-small.jpg';
}
如果图像位于不同的服务器上,这很有效。更多here。