上传html文件并在上传之前在thymeleaf中显示html文件预览

3pmvbmvn  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(440)

我正在开发一个springboot项目,它使用thymeleaf作为前端。我给用户一个选项,上传一个html(纯html)文件和要求,也是显示预览的html文件之前上传。我可以看到在互联网上有选择预览图像,但我找不到一些html文件预览的例子。有人能帮我做到这一点吗?

<div class="col-md-8 mx-auto">
                <h2>Upload Email Template</h2>
                <p th:text="${message}" th:if="${message ne null}" class="alert alert-primary"></p>
                <form method="post" th:action="@{/upload}" enctype="multipart/form-data">
                  <div class="form-group">
                    <input type="file" name="file" class="form-control-file">
                  </div>
                  <button type="submit" class="btn btn-primary">Upload File</button>
                </form>
              </div>

控制器

@PostMapping("/upload")
    public String uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes attributes) {

        // check if file is empty
        if (file.isEmpty()) {
            attributes.addFlashAttribute("message", "Please select a file to upload.");
            return "redirect:/";
        }

        // normalize the file path
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());

        // save the file on the local file system
        try {
            Path path = Paths.get(UPLOAD_DIR + fileName);
            Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
            log.info("file upload successful" +path);
        } catch (IOException e) {
            e.printStackTrace();
        }

        // return success response
        attributes.addFlashAttribute("message", "You successfully uploaded " + fileName + '!');

        return "redirect:/monthlyTransactions";
    }
jdg4fx2g

jdg4fx2g1#

我用下面的方法解决了上面的问题

<form id="form1" runat="server">
    <input type="file" onchange="preview()">
    <div class="frame" ></div>
    <div id="frame" src="" width="100px" height="100px"/>
  </form>

   function preview() {
frame.src=URL.createObjectURL(event.target.files[0]);
$('div.frame').load(frame.src);
  }

 div.frame{
width:100%;
height:100%;
border:solid #000 1px;
 }

相关问题