如何将图像上传到 tomcat 或 glassfish 中的网络资源文件夹

How to upload an image to web resource folder in tomcat or glassfish

我尝试将图像上传到 tomcat 和 glassfish 服务器,我尝试设置的路径如下 System.getProperty("user.dir")+ File.separator+"images"+File.separator;

它将 System.getProperty("user.dir") 作为 tomcat C:\Apache\Tomcat\bin 和 glassfish 'C:\Apache\glassfish4\glassfish\domains\domain1\config` 目录。我正在使用 Intellij 来开发系统。

我想上传一张图片到 out/artifacts/CopywriteProtector_war)exploded/Resources/images 文件夹,这样我就可以使用 http://localhost/Resources/images/msg.jpg 访问这些图片,该怎么做?我花了几天时间谷歌搜索但无法找到有用的东西

您可以使用

获取已部署应用程序的根目录
String root = getServletContext().getRealPath("/");

这相当于您的源代码的资源目录。 添加您希望图像所在位置的文件路径。即

String filePath = root + "images/msg.jpg";

然后你可以从那个路径创建你的作者

BufferedWriter writer = new BufferedWriter(new FileWriter(filepath);
writer.write(objectToWrite);//or similar

然后您可以使用

访问生成的文件
getServletContext().getResource(filePath); // as URL or
getServletContext().getResourceAsStream(filePath); // as InputStream

-- 在 Payara(从 Glassfish 派生的应用程序服务器)上测试和工作