如何创建包含内容的文件并使用 THYMELEAF 下载

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

我正在使用 thymeleaf 开发一个 spring 引导项目,我需要创建一个文件并在其中添加一些行,然后将其发送给用户下载。

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

因此,如果您想要 return 一个文件,您可能希望对其进行流式处理以限制使用的内存量(或者至少这可能是 Spring 框架创建者的推理)。在您的情况下,我知道该文件很小,实际上不必在任何地方保留。这只是基于上传表格的一次性下载,对吧?

所以这种方法适用于我的电脑:

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

注意 content-disposition header。它明确指出您不想在浏览器中显示文件,而是希望将其作为文件下载,myquery.sql 是将要下载的文件的名称。

@Kamil janowski

这是现在的样子

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