简体   繁体   中英

Spring boot and thymeleaf - upload and display image

I'm making a simple spring boot app with Thymeleaf. I have a controller to upload images, it's saving in project folder uploads . Can please someone explain to me how can I display it instantly after uploading it? Should I use @PostMapping or just some Thymeleaf tag?

My controller class

@Controller
public class UploadFileController {
    public static String uploadDirectory = System.getProperty("user.dir") + "/uploads";

    @RequestMapping("/")
    public String uploadPage(Model model) {
        return "uploadview";
    }

    @RequestMapping("/upload")
    public String upload(Model model, @RequestParam("files")MultipartFile[] files) {
        StringBuilder fileNames = new StringBuilder();

        for(MultipartFile file : files) {
            Path fileNameAndPath = Paths.get(uploadDirectory, file.getOriginalFilename());
            fileNames.append(file.getOriginalFilename());
            try {
                Files.write(fileNameAndPath, file.getBytes());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        model.addAttribute("msg", "Uploaded files: " + fileNames.toString());
        return "uploadstatusview";
    }


UPDATE I'm adding screenshots how it should look.

  1. Choose file
  2. Chosen file eg test1.png - Upload file
  3. Than its sending me on another html template with upload endpoint. To this point it's working. Picture it's saving in project but now I wanna see this picture like it's on screenshot want it to be like that

If I understood correctly, you want to get newly uploaded images by request at separate url. You can store images into List or Queue when handling upload, and then, by request, compile template for each image stored in List
Your template might look like:

<img src="${imgPath}" />

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