Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a text file with Spring MVC?

@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.

like image 806
Mythul Avatar asked Dec 12 '22 13:12

Mythul


1 Answers

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.

like image 127
Farid Avatar answered Jan 02 '23 02:01

Farid