繁体   English   中英

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

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

我正在用 Thymeleaf 制作一个简单的 Spring Boot 应用程序。 我有一个控制器来上传图像,它保存在项目文件夹uploads 中 请有人向我解释如何在上传后立即显示它? 我应该使用 @PostMapping 还是只使用一些 Thymeleaf 标签?

我的控制器类

@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";
    }


更新我正在添加屏幕截图。

  1. 选择文件
  2. 选择的文件,例如 test1.png - 上传文件
  3. 比它发送给我另一个带有上传端点的 html 模板。 到目前为止,它正在发挥作用。 图片它正在保存在项目中,但现在我想看到这张图片就像它在屏幕截图上一样希望它像那样

如果我理解正确,您希望通过单独的 url 请求获取新上传的图像。 您可以在处理上传时将图像存储到 List 或 Queue 中,然后根据请求,为存储在 List 中的每个图像编译模板
您的模板可能如下所示:

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

暂无
暂无

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

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