Send file for download with ajax

No matter there are sources that state downloading a file with AJAX is not possible there are many queries to do that and of course there is a way to do it.

Downloading a file with AJAX has a trick that works on a majority of browsers. One have to post parameters with AJAX, do some server process to prepare the file and then have two options:

  1. Return the data (file contents) and use it to return a file for download
  2. Save the file on the server and return a link with a parameter, that will return the file for download with the appropriate headers set.

1. The first option is OK if you handle very small files (up to 1MB). The possend some parameters to the server, file is prepared by querying a database, done some calculation etc. and then the file contents are returned. You can handle the contents as a AJAX response from the server and use them to set them as a value of a hidden input, then post again to an address where the posted parameters are returned with appropriate headers set. This works for very smaller files and is not an option, because it doubles the time for response.

2. The second option is to post the parameters to the server with AJAX, do the process of preparing the file and save it on the server. Then return only the link of an address that will return the file with download headers set. This option also has a drawback – If there are a lot of files to download, there have to be a cron job for deleting the old files.
Here is an example code in the client:

<iframe id="frm"></iframe>
<style>iframe#frm {display: none;}</style>
<script>
$("#my_form").live('ajax:success', function(event, data, status, xhr) {
    if (data.filename) {
      url = "/download_file?filename=" + data.filename
      $('#frm').src = url
      window.location = url
    } else {
      alert('No data to display')
    }
});
</script>

The server code depends on your needs, but here is an example for the download_file URL in Rails

filename = sanitize_filename params[:filename]
file = Rails.root.to_s + "/tmp/downloads/" + filename
send_file file, :filename => filename, :disposition => 'attachment', :type => 'application/x-www-form-urlencoded'
Tagged with: , , ,
Posted in Articles, Browsers, JavaScript, Ruby On Rails

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Sites
Categories
Archives