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

huangapple go评论138阅读模式
英文:

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

问题

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

    //某些代码 ..........

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

    //在这里我需要创建一个带有行列表的文件

    //并且还需要添加一些代码来进行下载

    return "filegenerator";
}
英文:

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(&quot;/filegenerator&quot;)
public String createFile(@ModelAttribute(&quot;page&quot;) Page page, Model model) {
    List&lt;String&gt; lines = new ArrayList&lt;String&gt;();

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

    lines.forEach(l-&gt;{
        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 &quot;filegenerator&quot;;
}

答案1

得分: 3

如果您想要返回一个文件,您可能希望将其以流的方式传输,以限制内存的使用量(或者至少这可能是Spring Framework创建者的推理)。在您的情况下,我理解该文件相当小,实际上不需要持久化存储在任何地方。这只是基于上传表单的一次性下载,对吗?

所以这种方法在我的电脑上有效:

@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 标头。它明确表示您不希望在浏览器中显示文件,而是希望将其作为文件下载,myquery.sql 是将要下载的文件的名称。

英文:

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(&quot;/filegenerator&quot;)
public void createFile(HttpServletResponse response) throws IOException {
    List&lt;String&gt; lines = Arrays.asList(&quot;line1&quot;, &quot;line2&quot;);
    InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining(&quot;\n&quot;)).getBytes());
    IOUtils.copy(is, response.getOutputStream());
    response.setContentType(&quot;application/sql&quot;);
    response.setHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;myquery.sql\&quot;&quot;);
    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.

答案2

得分: 1

@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().equals("")) {
            List<String> output = so.createTable(page.getTables());
            output.forEach(line -> lines.add(line));
        }
        if (!page.getInserttables().get(0).getName().equals("")) {
            List<String> output = so.insert(page.getInserttables());
            output.forEach(line -> lines.add(line));
        }
        if (!page.getUpdatetables().get(0).getName().equals("")) {
            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";
    }
英文:

@Kamil janowski

This is how it looks like now

@PostMapping(&quot;/filegenerator&quot;)
public String createFile(@ModelAttribute(&quot;page&quot;) Page page, Model model,HttpServletResponse response) throws IOException{
List&lt;String&gt; lines = new ArrayList&lt;String&gt;();
if(page.getTables().get(0).getName()!=&quot;&quot;) {
List&lt;String&gt; output = so.createTable(page.getTables());
output.forEach(line -&gt; lines.add(line));
}
if(page.getInserttables().get(0).getName()!=&quot;&quot;) {
List&lt;String&gt; output = so.insert(page.getInserttables());
output.forEach(line -&gt; lines.add(line));
}
if(page.getUpdatetables().get(0).getName()!=&quot;&quot;) {
List&lt;String&gt; output = so.update(page.getUpdatetables());
output.forEach(line -&gt; lines.add(line));
}
lines.forEach(l-&gt;{
System.out.println(l);
});
InputStream is = new ByteArrayInputStream(lines.stream().collect(Collectors.joining(&quot;\n&quot;)).getBytes());
IOUtils.copy(is, response.getOutputStream());
response.setContentType(&quot;application/sql&quot;);
response.setHeader(&quot;Content-Disposition&quot;, &quot;attachment; filename=\&quot;myquery.sql\&quot;&quot;);
response.flushBuffer();
model.addAttribute(&quot;page&quot;, getPage());
return &quot;filegenerator&quot;;
}		

huangapple
  • 本文由 发表于 2020年5月30日 19:05:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/62101513.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定