如何在Tomcat服务器上保存和加载映像

时间:2013-03-20 21:58:20

标签: java image tomcat java-ee

我正在编写Java EE应用程序,我尝试从URL获取图像,然后将其保存在我的资源文件夹中(通过AJAX请求)。 我的问题是,如果我不重新启动我的服务器,我将无法显示此图像,因为它未加载到我的服务器上。

我正在使用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");

如何在不重启的情况下自动加载我的上传图片? 哪个文件允许配置上传文件夹?怎么样?

1 个答案:

答案 0 :(得分:3)

您不应该将动态检索到的图像写入您的webapp文件夹 - 这样可以解决一大类问题。而是将它们保存到appserver根目录之外的文件夹中,并创建一个将为这些资源提供服务的下载servlet。

否则,您将从外部源检索一些jsp文件,将它们保存到您的应用程序服务器,并在下载时,appserver将很乐意在服务器端执行它。

假设您的webapp目录不能写入您的webapp。这也将简化备份和更新:想象一下,您需要安装更新或迁移到其他服务器:您的服务器上的应用程序将仅部分包含在其* .war文件中。如果有明确的资源目录,您可以单独备份(或将其放在网络共享驱动器上)