简体   繁体   English

Spring boot 和 thymeleaf - 上传和显示图片

[英]Spring boot and thymeleaf - upload and display image

I'm making a simple spring boot app with Thymeleaf.我正在用 Thymeleaf 制作一个简单的 Spring Boot 应用程序。 I have a controller to upload images, it's saving in project folder uploads .我有一个控制器来上传图像,它保存在项目文件夹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?我应该使用 @PostMapping 还是只使用一些 Thymeleaf 标签?

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选择的文件,例如 test1.png - 上传文件
  3. Than its sending me on another html template with upload endpoint.比它发送给我另一个带有上传端点的 html 模板。 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.如果我理解正确,您希望通过单独的 url 请求获取新上传的图像。 You can store images into List or Queue when handling upload, and then, by request, compile template for each image stored in List您可以在处理上传时将图像存储到 List 或 Queue 中,然后根据请求,为存储在 List 中的每个图像编译模板
Your template might look like:您的模板可能如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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