简体   繁体   中英

Upload html file and show the html file preview in thymeleaf before uploading

I am developing a spring boot project which uses Thymeleaf as the front end. I am giving the user an option to upload a html(plain html) file and the requirement is also to show the preview of html file before uploading. I could see in the internet there are option to preview an image but i cannot find some example for html file preview. Can someone please help me achieve this?

<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>

controller

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

I solved the above using like below

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

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