【发布时间】:2017-06-27 12:24:52
【问题描述】:
我在同一个 tomcat 实例上运行了 3 个 Web 应用程序,一个应用程序 (ZaapMartAdmin) 供管理员将文件上传到另一个应用程序的 (ImageUploads) 目录,而第三个应用程序(ROOT)只是读取上传到(ImageUploads)的文件并从那里显示图像文件。 我从here、here、here 和here 那里得到了一些想法。
这是我的 servlet 中的相关代码(请注意:servlet 在 ZaapMartAdmin 上运行):
//...
String fileName = generateFileName(request);//Generate the image file name
byte[] imageBytes = getByteArray(request);//Generate the image bytes
//Where to save the image part
ServletContext adminContext = request.getServletContext();//ZaapMartAdmin context
ServletContext rootContext = adminContext.getContext("/");//ROOT context
ServletContext uploadsContext = rootContext.getContext("/ImageUploads");//ImageUploads context
String absolutePath = uploadsContext.getRealPath("");
File imagesDirectory = new File(absolutePath + File.separator + "images");
if(!imagesDirectory.exists())
imagesDirectory.mkdir();
try(FileOutputStream fos = new FileOutputStream(absolutePath + File.separator + "images" + File.separator + fileName);)
{
fos.write(imageBytes);//<-- store the image in the directory
//... store file name to database ...
}
//...
从服务器端看,我的目录结构如下:
现在的问题是,当我运行这个 servlet 时,文件将保存在“ZaapMartAdmin”目录而不是“ImageUploads”目录中。 而且它不会抛出任何异常。
我还在每个应用的 context.xml 中添加了crossContext="true"。
请问我在这里做错了什么?
【问题讨论】:
-
只需将文件保存在外部目录中。这样,如果您重新部署您的应用程序,将不会被删除。
-
那太棒了,但是不通过应用程序我怎么能做到呢?
-
您是否尝试过使用绝对路径,例如:´new File(/var/tomcat/data/images);´?