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

3 Answers 3

13

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

2 Comments

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 ?
@AllTooSir when you add the annotation over your API method inside the controller @GetMapping(value = "/url", produces = MediaType.APPLICATION_OCTET_STREAM)
0

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");  

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.