Java Spring: create a file and offer this for download via api

Asked

Viewed 649 times

0

Hello

I have some documents saved in the database (with equivalent templates, they are not .txt files or anything), I would like to create . txt and . Md from the database, searching for the template, extracting the title and content to form a file and adding an extension, and then offering that file for download.

I find many examples of file downloads, this would only be a part, the first would be to generate a custom file only when requested by the client.

Where I could find examples based on this?

Thank you.

Document.java

...
    @Id
    @GeneratedValue
    private Long id;

    private String title;

    private String description;
}

1 answer

0


Well, I found a way to do, I do not know if it is the most correct, but this function is returning me the link of the generated file.

Documentcontroler.java

//passo o título do arquivo que tenho salvado no banco de dados
@GetMapping("/download/title={title}")
public File download(@PathVariable("title") String title) {
    Document document = service.findByTitle(title);
    //busco o documento pelo título

    File file = new File(title + ".txt");
    //adiciono o título como nome do arquivo

    try (Writer writer = new BufferedWriter(new FileWriter(file))) {
        String contents = document.getDescription();
        writer.write(contents);
        //adiciono o conteúdo do documento ao arquivo

        return file;
        //retorno a url onde ele foi gerado.

    } catch (IOException e) {
        e.printStackTrace();
    }

    return null;
}

Then just access the url and download the file.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.