12

I am fairly new to AJAX. I am sending a request to server using AJAX. The service returns a text file. But no download box appears when data is returned. The rest service that returns the file is as follows:

@Path("/examples")
public class ExampleCodesRest {


    @POST
    @Path("/getcode")
    @Produces(MediaType.TEXT_PLAIN)
    public Response getCodes(@Context ServletContext context){

        String in=context.getRealPath("/WEB-INF/reports.jrxml");
        File file=new File(in);

        ResponseBuilder response = Response.ok((Object) file);
        response.header("Content-Disposition",
            "attachment; filename=\"file_from_server.log\"");
        return response.build();

    }
}

My AJAX call is as follows:

 $('a#link').click(function(event){
    event.preventDefault();
    $.ajax({
        url: '/reports/rest/examples/getcode',
        type: 'POST'
    });
}); 

The file downloads successful without AJAX. With AJAX, it doesn't download the file.Please advice.

Mono Jamoon
  • 4,437
  • 17
  • 42
  • 64
  • possible duplicate of [Handle file download from ajax post](http://stackoverflow.com/a/23797348/148271) – IsmailS Jan 19 '15 at 15:14

3 Answers3

18

Advice is simple: you cannot download files via AJAX - it's a security policy. I mean you can download the data, but you can't save it to disk from JavaScript side.

If you want to download a file on click, then you can just add href to you a tag. Or open a new window with file's URL.

freakish
  • 54,167
  • 9
  • 132
  • 169
  • Thanks for the reply. After some research it seems that at most I can open a window to show the contents but I cannot save it to disk. – Mono Jamoon Oct 18 '12 at 13:20
1

A) you don't have a callback to receive data back
b) Add error callback to you code so you can see if there are receiving errors after the call:

    $.ajax({
    url: '/spaconsole/rest/examples/getcode',
    type: 'POST'
    success: function (data) {
        console.log('ok');
    },
    error: function (xhr) {
      console.log(xhr);
    }
    });

Edit: This is if you want to display the text in page. If you want to download the file, this is not the way, you cannot use ajax

Draykos
  • 773
  • 7
  • 16
  • Thanks for the reply. I am getting the data from the server end but there is no prompt to save the data on-to disk. – Mono Jamoon Oct 18 '12 at 13:05
1

You can't do that directly from AJAX, but you can get around it by having an iframe that initiates the download. See Ajax File download Issue for a discussion.

Community
  • 1
  • 1
Palpatim
  • 9,074
  • 35
  • 43