Search code examples
javaspring-bootthymeleafeclipse-jee

How to create a file with content and download it with THYMELEAF


I'm working on a spring boot project with thymeleaf and I need to create a file and put some lines on it then send it for the user to download it.

@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model) {
    List<String> lines = new ArrayList<String>();

    //Some code ..........

    lines.forEach(l->{
        System.out.println(l);
    });

    //Here I need to create a file with the List of lines

    //And also put some code to download it        

    return "filegenerator";
}

Solution

  • So if you want to return a file, you probably want to stream it to limit the amount of memory used (or at least that was probably the reasoning of Spring Framework creators). In your case I understand that the file is fairly small and doesn't really have to be persisted anywhere. It's just a one time download based on the uploaded form, right?

    so this approach worked on my PC:

    @PostMapping("/filegenerator")
    public void createFile(HttpServletResponse response) throws IOException {
        List<String> lines = Arrays.asList("line1", "line2");
        InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining("\n")).getBytes());
        IOUtils.copy(is, response.getOutputStream());
        response.setContentType("application/sql");
        response.setHeader("Content-Disposition", "attachment; filename=\"myquery.sql\"");
        response.flushBuffer();
    }
    

    note the content-disposition header. It explicitly states that you don't want to display the file in the browser, but instead you want it to be downloaded as a file and myquery.sql is the name of that file that will be downloaded.