Spring – 如何将文件夹中的图像上传到数据库

huangapple go评论153阅读模式
英文:

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(&quot;static/anImage.jpg&quot;); 
byte[] bytes = resource.getInputStream().readAllBytes();

huangapple
  • 本文由 发表于 2020年7月22日 21:57:53
  • 转载请务必保留本文链接:https://go.coder-hub.com/63035956.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定