0

I want to download MS Word file with an AJAX post request.

So here is my Java code

 response.setContentType("application/ms-word");
 response.setHeader("Content-Disposition", "attachment; filename="+childName+".docx");
 OutputStream opStream = response.getOutputStream();

The service name is "/getAdmissionAgreement" and it is post request. Now this is how I am downloading the file using ajax post request:

$.ajax({
    type: "POST",
    url: url,   
    cache: false,
    success: function (response) {
        alert('got response');
        window.open(response);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
        alert('Error occurred while opening fax template' + getAjaxErrorString(textStatus, errorThrown));
    }
});

Now the problem is that the stream is coming but it is getting displayed in the browser's console and not coming as an downloadable file.

halfer
  • 19,824
  • 17
  • 99
  • 186
Nikhil Agrawal
  • 26,128
  • 21
  • 90
  • 126
  • You can't download a file via AJAX. See [this question](http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax) for more information. – Rory McCrossan Jul 07 '14 at 07:54
  • @RoryMcCrossan Thanks for your reply. So how can we download it with post request. Is there any other way. – Nikhil Agrawal Jul 07 '14 at 07:55
  • possible duplicated thread you need to refer here [how to download using ajax][1] [1]: http://stackoverflow.com/questions/4545311/download-a-file-by-jquery-ajax – Keluang Yang Ko Kenal Jul 07 '14 at 07:58

1 Answers1

1

After Ajax successfully executed u can append dynamic link with file .

var a = $("<a>").attr("href", "https://i.stack.imgur.com/L8rHf.png").attr("download", 

 "img.png").appendTo("body");
  //force click on link 
  a[0].click()

or set,

window.location="path"
anam
  • 3,905
  • 16
  • 45
  • 85