[英]How to check if image file exists in classpath through gwt client side?
I am creating an Image
object to which I want to set url of an image dynamically. 我正在创建一个
Image
对象,要向其动态设置图像的url。
Image img = new Image();
if(vehicleType.equals("car"))
img.setUrl(images/car.png);
else
img.setUrl("");
Here, I don't know if car.png
exists in my images folder in classpath. 在这里,我不知道
car.png
存在于类路径中的images文件夹中。 How can I check for its existence? 我如何检查它的存在? I want to set default vehicle image to the object if
car.png
is not on classpath. 如果
car.png
不在classpath上,我想将默认的车辆图像设置为该对象。
Thanks 谢谢
You can't check if an image is on the class path from the client side. 您无法从客户端检查图像是否在类路径上。
What you can do is add an ErrorHandler
to the Image
with its addErrorHandler()
method so you can detect if the browser can't load the image (because it doesn't exist on the server side for example). 您可以执行的操作是使用其
addErrorHandler()
方法向Image
添加一个ErrorHandler
,以便您可以检测浏览器是否无法加载该图像(例如,因为该图像在服务器端不存在)。
Image img = new Image();
img.setUrl("SET YOUR URL");
img.addErrorHandler(new ErrorHandler() {
@Override
public void onError(ErrorEvent e){
// Failed to load image
}
});
Note: there is also an Image.addLoadHandler()
method which you can use to detect when an image is loaded. 注意:还有一个
Image.addLoadHandler()
方法,可用于检测何时加载图像。
Another way could be to create a method at server side that is published in a service which checks if the image is availabe, and call this method from your client code. 另一种方法是在服务器端创建一个在服务中发布的方法,该方法检查图像是否可用,然后从客户端代码中调用此方法。
A Side Note 旁注
If you're the one that writes the client code and you tell the image url to be images/car.png
and you're the one that assembles server side resources, this shoudln't happen. 如果您是编写客户端代码的人,并且告诉图像url为
images/car.png
并且您是汇编服务器端资源的人,则应该不会发生这种情况。 At production environment you shouldn't use such checks. 在生产环境中,您不应使用此类检查。 If you somewhere write
img.setUrl("images/car.png")
you should make car.png
available at the server side and not bother with such runtime client side checks. 如果您在某处编写
img.setUrl("images/car.png")
,则应使car.png
在服务器端可用,而不必在运行时客户端进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.