Java 为什么getClass().getProtectionDomain().getCodeSource().getLocation().getPath()不';编译后的最终产品不工作?

Java 为什么getClass().getProtectionDomain().getCodeSource().getLocation().getPath()不';编译后的最终产品不工作?,java,Java,好的,这是我的网络项目。我在eClipse中使用以下结构构建了它: workspace3\MyProject\war\images\uploaded workspace3\MyProject\war\WEB-INF\classes 好的,我想将上传的图像存储到workspace3\MyProject\war\images\unload中,下面是服务端的代码&它在Eclipse中运行良好 String absolutePath = getClass().getProtectionDomain()

好的,这是我的网络项目。我在eClipse中使用以下结构构建了它:

workspace3\MyProject\war\images\uploaded
workspace3\MyProject\war\WEB-INF\classes
好的,我想将上传的图像存储到
workspace3\MyProject\war\images\unload
中,下面是服务端的代码&它在Eclipse中运行良好

String absolutePath = getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
absolutePath=absolutePath.replace("WEB-INF/classes/", "images/uploaded");
File file = File.createTempFile("upload-", "."+extName, new File(absolutePath));
好的,现在我编译了我的项目,并将其与Tomcat服务器一起放入VPS中,它具有以下结构

tomcat7\webapps\ROOT\images\uploaded
tomcat7\webapps\ROOT\WEB-INF\classes
然而,不知何故,当通过互联网运行网站时,它找不到
图片\上传的位置

我做错什么了吗? 为什么编译后的最终产品中
getClass().getProtectionDomain().getCodeSource().getLocation().getPath()
不起作用?

您应该使用以下命令来确定web应用程序的文件系统路径:

String absolutePath = request.getServletContext().getRealPath("/images/uploaded");
// File uploaded to this directory will be accessible via
// `http://<yourserver>/<web-app>/images/uploaded/`
请注意,此目录仅为临时目录,可能无法在服务器重新启动后继续存在!因此,这不是持久的坚持


最明智和持久的解决方案是将文件写入数据库或任何其他存储库(例如,like),或写入不受web服务器控制的文件目录(并从外部指定,例如通过系统属性或在
web.xml
中指定).

我需要在web.xml中执行任何操作吗?如果操作正确,那么在打开mydomain.com/images/upload/pic1.png时将显示image@Tum不,您不必为此更改web.xml,而且是的,第一个解决方案将使您上传的图像可用于web,如前所述。
File tempDir = (File)request.getServletContext().getAttribute(ServletContext.TEMPDIR);
// Files uploaded to that directory will NOT be automatically published to WWW.