Browser does not create file upload dialog

My current scenario is that the JavaScript client has a bunch of data that I POST to the server processes / translates into different formats (for example, CSV), now I want to send this converted data from the server to the client.

I set the content type of the response, but the browser does not create a file dialog box.

This is what my controller looks like:

@RequestMapping(value="/exportBoxes/{type}/{filename:.+}", method=RequestMethod.POST) public String exportBoxes(@RequestBody String body, @PathVariable String type, @PathVariable String filename, HttpServletResponse response) throws IOException { JsonObject jsonObject = new JsonParser().parse(body).getAsJsonObject(); //grab the data from the JSONobject String data = jsonObject.get("JSONdata").getAsString(); //create output stream writer PrintWriter p = new PrintWriter(response.getOutputStream()); //set response type and print header if(type.equals("csv")) { response.setContentType("text/csv"); response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\""); } //print the points to the file for(int i = 0; i < splitPoints.length; i++) { //print remainder of CSV file - abstracted } p.flush(); //flush the stream response.flushBuffer(); p.close(); //close the stream return "success"; } 

And here is the client function that sends the data:

 DAService.prototype.exportBoxes = function(type, filename, data) { var path = 'api/rest/da/exportBoxes/' + type + '/' + filename var url = (this.connection) ? this.connection + path : path; var JSONdata = ''; var returnType = '' //create JSON string to pass to Java controller if(type == 'csv') { JSONdata = '{ "JSONdata" : "' + data.replace(/ /g, '') + '" }'; returnType = 'text/csv'; } else { throw "Invalid export format " + type; } $j.ajax({ url: url, contentType: 'application/json', type: 'POST', dataType: returnType, data: JSONdata, success: function(returnedData){ console.log("exportBox successful"); }, error: function(x,y,z) { console.log("exportBox failed with error '" + y + "'"); }, complete: function(empty, textStatus){ console.log("exportBox complete textStatus='" + textStatus + "'"); } }); }; 

No errors are generated by this code, and the server response has a CSV file in it, I just can not get the client to generate a download dialog.

There is one thing that I am missing that I do not see if anyone can help me?

+4
source share
1 answer

You might want to try posting the form instead of using $.ajax :

 var form = $('<form/>', { action: url, method: 'POST', css: { display: 'none' }, html: $('<input/>', {name: 'JSONdata', value: data.replace(/ /g, '') }) }); $('body').append(form); form.submit(); 

(I have not tested this.) The fact is that when you really publish the form, the browser knows how to interpret the body of the response, and it should notice your attachment.

+3
source

All Articles