我正在编写Java EE应用程序,并尝试从URL获取图像,然后将其保存在我的资源文件夹中(通过AJAX请求)。 我的问题是,如果我不重新启动我的服务器我无法显示这个图像,因为它没有加载到我的服务器上。如何在Tomcat服务器上保存并加载图像
我使用的是Tomcat 7,Spring,Hibernate,Primeface。
这里是我的课,以节省MYIMAGE
public class ImageSaver {
final static int SIZE=1024;
public static void fileUrl(String fAddress, String localFileName, String destinationDir) {
OutputStream outStream = null;
URLConnection uCon = null;
InputStream is = null;
try {
URL url = new URL(fAddress);
byte[] buf;
int byteRead;
int byteWritten=0;
outStream = new BufferedOutputStream(new FileOutputStream(destinationDir+"\\"+localFileName));
uCon = url.openConnection();
is = uCon.getInputStream();
buf = new byte[SIZE];
while ((byteRead = is.read(buf)) != -1) {
outStream.write(buf, 0, byteRead);
byteWritten += byteRead;
}
}
catch (Exception e) {
e.printStackTrace();
}
finally {
try {
is.close();
outStream.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
public static void fileDownload(String fAddress,String fileName, String destinationDir){
int slashIndex =fAddress.lastIndexOf('/');
int periodIndex =fAddress.lastIndexOf('.');
//String fileName=fAddress.substring(slashIndex + 1);
if (periodIndex >=1 && slashIndex >= 0 && slashIndex < fAddress.length()-1){
}
else{
System.err.println("path or file name.");
}
}
}
和我的方式调用函数:
ImageSaver.fileDownload("http://www.mywebsite.com/myImage.jpg","myImage.jpg", "C:\\Users\\MyProject\\src\\main\\webapp\\resources\\images");
我怎样才能自动在我为我上载的图片加载,没有任何重新启动? 哪个文件允许配置上传文件夹?如何 ?
嗯,我已经试过这种方法,但我认为不是一个好方法。 如何“连接”我的文件夹到我的webapp?我的意思是,如果我将图像存储在_C:/ image_中,那么如果使用路径_C:/image/myimage.jpg_将其显示在我的JSP中(实际上我使用XHTML但它不是重点),它将无法工作。 我已经在_web.xml_中读过一些关于过滤器的地方,我们可以指定一个上传文件夹。这是一个好的解决方案吗?如果是,它是如何工作的? 感谢您的回答 – Tako 2013-03-21 11:06:26
我认为我的问题的回应是[这里](http://stackoverflow.com/questions/1812244/simplest-way-to-serve-static-data-from-outside-the-application- server-in-a-java/1812356#1812356) – Tako 2013-03-21 15:27:51
是的,看起来像一个确切的副本。感谢您的链接 – 2013-03-21 16:37:36