简体   繁体   中英

How to download html page with Rest api response

I have a html file in spring boot located at src/main/resources/templates/MyFile.html.

I tried with Thymeleaf and tried sending response in html page. But its not working. Below is the sample code.

My RestContreoller method is

    @RequestMapping(value = "/display", method = RequestMethod.GET)
    public ModelAndView getEmployee(@ModelAttribute String employee)
    {
            ModelAndView mav = new ModelAndView();
            mav.setViewName("MyFile");

            mav.addObject("employeeList", "employee");
            return mav;
    }

And my HTML page is

    <!DOCTYPE HTML>
    <html xmlns:th="http://thymeleaf.org">
    <head>
    <meta charset="UTF-8" />
    <title>Display Employee Details</title>
    </head>
    <body>
        <table border="1">
            <tr>
                <th>Name</th>
                <th>Age</th>
            </tr>

        </table>
    </body>
    </html>

When I invoke a get api call from Swing application, it redirects to my spring boot application. From spring boot application I want to send response in a html page which is located inside spring boot application at src/main/resources/templates/MyFile.html. This html page should be downloaded at client's end.

  @RequestMapping(value = "/display", produces = MediaType.TEXT_HTML_VALUE,
    method = RequestMethod.GET)
    public ResponseEntity<String> saveEmployee(String employee)
    {
        String content =  "<html><body><h1>Hi there</h1></body></html>";

        String htmlFileName = "MyHtmlFile.html";

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.parseMediaType(MediaType.TEXT_HTML_VALUE));
        headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
        headers.set("Content-Disposition", "attachment; filename=" + htmlFileName);

        return new ResponseEntity<>(content, headers, HttpStatus.OK);
    }

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