How to return a text file with Spring MVC?

16,049

here is a sample:

@RequestMapping( method = RequestMethod.POST, 
    value = DataController.RESOURCE_PATH + "/file", 
    headers = "content-type=application/json" )
public void export( @RequestBody JSONObject json, HttpServletResponse response ) 
    throws IOException {
    String myString = "Hello";
    response.setContentType("text/plain");
    response.setHeader("Content-Disposition","attachment;filename=myFile.txt");
    ServletOutputStream out = response.getOutputStream();
    out.println(myString);
    out.flush();
    out.close();
}

PS: don't forget to put some random stuff in your url (as parameter for example) to ensure your browser does not cache the text file.

Share:
16,049

Related videos on Youtube

Mythul
Author by

Mythul

Currently studying Computer Science at University.

Updated on September 15, 2022

Comments

  • Mythul
    Mythul over 1 year
    @RequestMapping( method = RequestMethod.POST, value = DataController.RESOURCE_PATH + "/file", headers = "content-type=application/json" )
    @ResponseBody
    public void export( @RequestBody JSONObject json, HttpServletResponse response ) throws IOException
    {
        String myString = "Hello";
    }
    

    The string is generated inside the Controller. What I want is to send back to the user a Window where he can save a file which contains the myString.

    $.ajax({
        type: "POST",
        url: url,
        data: JSON.stringify(createJSON()),
        contentType: "application/json",
        success: function(response)
        {
            console.log("Exported JSON: " + JSON.stringify(createJSON()));
            console.log(response);
        },
        error: function()
        {
            console.log(arguments);
            alert("Export process failed.");
        }
    });
    

    It clearly doesn't work in this current state and I am stuck at the moment.

  • AllTooSir
    AllTooSir almost 11 years
    Use where ? Secondly , can we download files using AJAX ? I'm not talking about displaying but downloading ! Thirdly , do you think the method export() works ?
  • veritas
    veritas over 2 years
    @AllTooSir when you add the annotation over your API method inside the controller @GetMapping(value = "/url", produces = MediaType.APPLICATION_OCTET_STREAM)