【发布时间】:2020-11-30 22:22:18
【问题描述】:
我已经部署了一个 spring-boot 应用程序 JAR 文件。现在,我想从android上传图像并将其存储在资源目录的myfolder中。但是无法获取资源目录的路径。
错误是: java.io.FileNotFoundException: src/main/resources/static/myfolder/myimage.png (没有这样的文件或目录)
这是在资源文件夹中存储文件的代码
private final String RESOURCE_PATH = "src/main/resources";
String filepath = "/myfolder/";
public String saveFile(byte[] bytes, String filepath, String filename) throws MalformedURLException, IOException {
File file = new File(RESOURCE_PATH + filepath + filename);
OutputStream out = new FileOutputStream(file);
try {
out.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
return file.getName();
}
更新:
这是我尝试过的
private final String RESOURCE_PATH = "config/";
controller class:
String filepath = "myfolder/";
String filename = "newfile.png"
public String saveFile(byte[] bytes, String filepath, String filename) throws MalformedURLException, IOException {
//reading old file
System.out.println(Files.readAllBytes(Paths.get("config","myfolder","oldfile.png"))); //gives noSuchFileException
//writing new file
File file = new File(RESOURCE_PATH + filepath + filename);
OutputStream out = new FileOutputStream(file); //FileNotFoundException
try {
out.write(bytes);
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
return file.getName();
}
项目结构:
+springdemo-0.0.1-application.zip
+config
+myfolder
-oldfile.png
-application.properties
+lib
+springdemo-0.0.1.jar
+start.sh
-springdemo-0.0.1.jar //running this jar file
【问题讨论】:
-
你不能,因为这是类路径的一部分。因此,您根本无法在其中存储某些内容(从 IDE 运行该类时它会起作用,但只是因为它是基于文件的,而不是在 JAR 或 WAR 中)。您只能将 tings 存储在常规文件位置。
-
如果我不能在资源文件夹中存储文件,还有什么选择?
-
将其存储在文件系统中一个众所周知的位置。您需要将其从 jar 存储在外部。
-
好的。我会试试的
标签: java spring spring-boot rest