Mythul
Mythul

Reputation: 1807

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.

Upvotes: 5

Views: 19846

Answers (3)

dwjohnston
dwjohnston

Reputation: 11900

I recommend using filesaver.js.

Then your solution will look like:

var text = JSON.stringify(createJSON());  
var blob = new Blob([text], {type: "text/plain; charset=utf-8"});                           
saveAs(blob, "myfile.txt");  

Upvotes: 0

asa
asa

Reputation: 4040

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.

Upvotes: 13

Juned Ahsan
Juned Ahsan

Reputation: 68715

To return a file you need to use the MediaType.APPLICATION_OCTET_STREAM as the response type.

Upvotes: 0

Related Questions