5

I use ExtJS to build the client-side for my program. There's a situation that I want to send an Ajax request to server, and get the response file (binary file, not plain text file, i.e XLS or PDF). How can I get that returned file by ExtJS (I mean that file can be downloaded and stored to client)? I cannot use var result = Ext.decode(response.responseText) to receive the result because reponse contains binary data and it cannot be decoded.

The Ajax call is very simple :

Ext.Ajax.request({
    url : 'myController/exportFile',
    method : 'GET',
    success : function(response, opts) {
        // What should I do to get the file?
    },
    failure : function(response, opts) {
        alert('Export file failed!')
    }
});

Here is my server action to return file:

public void sendFile(HttpServletResponse response, String filePath) {
        def file = new File(filePath);
        response.setContentType("application/octet-stream");
        response.setHeader("Content-disposition", "attachment;filename=${file.getName()}");     
        response.outputStream << file.newInputStream();
    }

Thank you so much!

Ashish Aggarwal
  • 3,018
  • 2
  • 23
  • 46
Đinh Hồng Châu
  • 5,300
  • 15
  • 53
  • 90

2 Answers2

2

If you need the user to be prompted with the typical browser provided open/save dialog box, you don't need to make this call AJAX.

Just linking to myController/exportFile from your page should be enough.
e.g. <a href="myController/exportFile">my file</a>

For this approach to work, HTTP response from myController/exportFile must include the appropriate headers (namely, Content-type and Content-disposition) that tell the browser "this is file. show open/save dialog" and based on your snippet, I see that you already have this taken care of.

Amol Katdare
  • 6,740
  • 2
  • 33
  • 36
  • Great answer! You are the best !! I've looked for this long time and only this post gave me proper answer! – davs Jul 28 '11 at 12:47
  • @amol can you please help me [here](http://stackoverflow.com/questions/8505995/itextsharp-generated-pdf-how-to-prompt-a-user-to-choose-where-to-save) – Armance Dec 15 '11 at 09:53
0

You can save your file to server's file-system and send window.open('http://your.domain/your/file') to client side... where http://your.domain/your/file -link to file

TheHorse
  • 2,787
  • 1
  • 23
  • 32