【问题标题】:Spring boot and thymeleaf - upload and display imageSpring boot 和 thymeleaf - 上传并显示图片
【发布时间】:2020-12-17 09:26:15
【问题描述】:

我正在使用 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 模板上发送给我。到目前为止,它正在工作。图片保存在项目中,但现在我想看到这张图片,就像它在屏幕截图上一样 want it to be like that

【问题讨论】:

  • 您上传文件夹中的图片是可以直接从网络访问还是只能通过服务访问?
  • 不,仅来自服务

标签: java spring-boot thymeleaf


【解决方案1】:

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

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

【讨论】:

    最近更新 更多