1

我正在使用以下代码从我的服务器获取图像:

<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 时,我该如何处理?

编辑:图像位于不同的服务器上。

4

2 回答 2

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>

这可能会导致您提供不需要的后备图像,而且它依赖于相同大小的图像。

于 2013-04-14T10:42:38.230 回答
0

onerror我使用 jquery 和属性解决了这个问题:

我的服务器端代码现在是:

<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';
}

如果图像位于不同的服务器上,这会很好地工作。更多在这里

于 2013-04-15T19:00:21.113 回答