Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why threre is no way to download file using ajax request?

In our application we need to implement following scenario:

  1. A request is send from client
  2. Server handles the request and generates file
  3. Server returns file in response
  4. Client browser displays file download popup dialog and allows user to download the file

Our application is ajax based application, so it would be very easy and convenient for us to send ajax request (like using jquery.ajax() function).

But after googilng, it turned out that file downloading is possible only when using non-ajax POST request (like described in this popular SO thread). So we needed to implement uglier and more complex solution that required building HTML structure of form with nested hidden fields.

Could someone explain in simple words why is that ajax requests cannot be used to download file? What's the mechanics behind that?

like image 778
Piotr Sobczyk Avatar asked Feb 04 '13 08:02

Piotr Sobczyk


People also ask

Why is AJAX success not working?

ajax post method. The reason was my response was not in the JSON format so there was no need for the dataType: 'json' line in the submit method. In my case, the returned response was in text format that's why it was not going to success event. Solution: Remove dataType: 'json' line.

How can I download Excel file in AJAX?

Downloading Excel File using AJAX in jQueryInside the DownloadFile JavaScript function, the URL of the File is passed as parameter to the jQuery AJAX function. Inside the jQuery AJAX function, using the XmlHttpRequest (XHR) call, the PDF file is downloaded as Byte Array (Binary Data).


1 Answers

It's not about AJAX. You can download a file with AJAX, of course. However the file will be kept in memory, i.e. you cannot save file to disk. This is because JavaScript cannot interact with disk. That would be a serious security issue and it is blocked in all major browsers.

like image 80
freakish Avatar answered Sep 22 '22 05:09

freakish