简体   繁体   中英

How to display a picture from a database in Spring?

I understand that this is a stupid question and on the Internet you can find examples of how to do this, but basically I found some too confusing code where I didn't understand anything... I have a blog database on the localhost, I successfully upload all the information for the post (name, date, text and picture) there. But I generally can't figure out how to display it from there. Maybe someone will not be too lazy and show at least a part of the code or the idea itself... Here I have a controller where I load information into the database

@PostMapping("addArticle")
public String postAddArticle(@AuthenticationPrincipal User user, Date timeArticle, @RequestParam String title, String author,
                             @RequestParam String anons, @RequestParam String text,
                             @RequestParam("file") MultipartFile file, Model model) {
    Byte[] bArray = null;

    author = user.getUsername();

    Calendar calendar = Calendar.getInstance();
    timeArticle = calendar.getTime();

    try {
        bArray = new Byte[file.getBytes().length];
        int i = 0;
        for(byte b : file.getBytes()){
            bArray[i++] = b;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

    Post post = new Post(title,timeArticle, author, anons, text, bArray );
    post.setTitle(title);
    post.setTimeArticle(timeArticle);
    post.setAuthor(author);
    post.setAnons(anons);
    post.setText(text);
    post.setImage(bArray);
    postRepository.save(post);

    return "redirect:/adminPage";
}

The code works and everything is successfully added to the database, including the image. Tell me how to display it with thymeleaf in the img tag now?

In a web application, normally you would add images to resources folder and these images will then be access via the application, if this suits you refer this: images as static resources . So once this application get packaged and extracted after deployment, images paths will be resolved and can be seen on browsers.

If you so want to store images in the database, you could try saving them as base64 encoded strings in the database, for that you could use this: base64 conversion

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM