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

Viewed 1231

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";
}
2 Answers

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.

@Kamil janowski

This is how it looks like now

@PostMapping("/filegenerator")
public String createFile(@ModelAttribute("page") Page page, Model model,HttpServletResponse response) throws IOException{

    List<String> lines = new ArrayList<String>();
    if(page.getTables().get(0).getName()!="") {
    List<String> output = so.createTable(page.getTables());
    output.forEach(line -> lines.add(line));
    }
    if(page.getInserttables().get(0).getName()!="") {
        List<String> output = so.insert(page.getInserttables());
        output.forEach(line -> lines.add(line));
    }
    if(page.getUpdatetables().get(0).getName()!="") {
        List<String> output = so.update(page.getUpdatetables());
        output.forEach(line -> lines.add(line));
    }

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

    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();

    model.addAttribute("page", getPage());
    return "filegenerator";
}       
Related