英文:
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;
}
英文:
Hello im trying to do something like this:
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;
}
But it's wrong. So how to pick up a file from specific directory? Thanks.
ps.
I can do something like this:
File file = new File("image.jpg");
byte[] content = Files.readAllBytes(file.toPath());
But still its a path only from the main folder. Dont know how to program for the resources/images folder.
答案1
得分: 1
不要重新发明轮子,例如使用Apache Commons将文件转换为字节数组。阅读更多FileUtils.readFileToByteArray(File input)。
您加载资源的方式似乎是正确的。
请确保加载的文件位于正确的位置(src/main/resources)。
您是否有任何特定的错误或堆栈跟踪描述了问题。
英文:
Don't reinvent the wheel and use e.g. Apache Commons for convert a File to byte array. Read more <a href="https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/FileUtils.html#readFileToByteArray(java.io.File)">FileUtils.readFileToByteArray(File input)</a>
The way you loading resources seems to be the proper one.
Ensure that the loaded file is in proper location (src/main/resources).
Do you have any particular error or stack trace which describes the issue.
答案2
得分: 1
在Spring中,您可以使用Resources来实现您的目标:
Resource resource = new ClassPathResource("static/anImage.jpg");
byte[] bytes = resource.getInputStream().readAllBytes();
英文:
In Spring you can use Resources to achieve your goal:
Resource resource = new ClassPathResource("static/anImage.jpg");
byte[] bytes = resource.getInputStream().readAllBytes();
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论