Spring - 如何将图片从文件夹上传到数据库
Spring - How to upload image from folder to database
你好,我正在尝试做这样的事情:
private Byte[] getImage() throws IOException {
String imageUrl = ServletContext.class.getClassLoader()
.getResource("static/anImage.jpg")
.getFile();
Byte[] byteObject = new Byte[imageUrl.getBytes().length];
int i = 0;
for (Byte b : imageUrl.getBytes()){
byteObject[i++] = b;
}
return byteObject;
}
但这是错误的。那么如何从特定目录中获取文件呢?谢谢
ps。
我可以这样做:
File file = new File("image.jpg");
byte[] content = Files.readAllBytes(file.toPath());
但它仍然是仅来自主文件夹的路径。不知道如何为 resources/images 文件夹编程。
不要重新发明轮子并使用例如Apache Commons 用于将文件转换为字节数组。阅读更多 FileUtils.readFileToByteArray(File input)
您加载资源的方式似乎是正确的。
确保加载的文件位于正确的位置 (src/main/resources)。
您是否有描述该问题的任何特定错误或堆栈跟踪。
在Spring中您可以使用Resources来实现您的目标:
Resource resource = new ClassPathResource("static/anImage.jpg");
byte[] bytes = resource.getInputStream().readAllBytes();
你好,我正在尝试做这样的事情:
private Byte[] getImage() throws IOException {
String imageUrl = ServletContext.class.getClassLoader()
.getResource("static/anImage.jpg")
.getFile();
Byte[] byteObject = new Byte[imageUrl.getBytes().length];
int i = 0;
for (Byte b : imageUrl.getBytes()){
byteObject[i++] = b;
}
return byteObject;
}
但这是错误的。那么如何从特定目录中获取文件呢?谢谢
ps。 我可以这样做:
File file = new File("image.jpg");
byte[] content = Files.readAllBytes(file.toPath());
但它仍然是仅来自主文件夹的路径。不知道如何为 resources/images 文件夹编程。
不要重新发明轮子并使用例如Apache Commons 用于将文件转换为字节数组。阅读更多 FileUtils.readFileToByteArray(File input)
您加载资源的方式似乎是正确的。
确保加载的文件位于正确的位置 (src/main/resources)。
您是否有描述该问题的任何特定错误或堆栈跟踪。
在Spring中您可以使用Resources来实现您的目标:
Resource resource = new ClassPathResource("static/anImage.jpg");
byte[] bytes = resource.getInputStream().readAllBytes();