Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger download with Rails send_data from AJAX post

Tags:

I'm trying to use send_data to return a PNG image as the response for a ajax post request. How do I get the browser to trigger a download on the success callback?

Details

I'm generating a large base64 image using canvas.toDataURL(), and then posting it to Rails (v3.2.6). Rails decodes it to a binary PNG, and sends the image back to the client.

I've also tried send_file but it has the same issue.

Other options

  1. Download image client side: We can't do this because (1) Safari crashes on large base64 URLs, and (2) Safari does not yet support the download attribute on anchor tags which I would need to specify the downloaded image filename.

  2. Use a $.get instead of $.post: We can't do this because we need to send our canvas.toDataURL() with the request to the server. GET requests URIs have size limitations.

like image 820
mayatron Avatar asked Apr 26 '13 17:04

mayatron


People also ask

How to make Ajax request to open the download prompt?

You can't have an AJAX request open the download prompt since you physically have to navigate to the file to prompt for download. Instead, you could use a success function to navigate to download.php. This will open the download prompt but won't change the current page.

How do I start a CSV file download from Ajax?

You can have the download started from inside an ajax function, for example, just after the .csv file is created. I have an ajax function that exports a database of contacts to a .csv file, and just after it finishes, it automatically starts the .csv file download. So, after I get the responseText and everything is Ok, I redirect browser like this:

How do I download a binary file from a website without Ajax?

You actually don't need ajax at all for this. If you just set "download.php" as the href on the button, or, if it's not a link use: The browser should recognise the binary download and not load the actual page but just serve the file as a download. The programming language you're using to change window.location is JavaScript.


2 Answers

create a function in controller

def ajax_download   send_file "path_to_file/" + params[:file] end 

and then in controller action

respond_to do |format|   @java_url = "/home/ajax_download?file=#{file_name}"   format.js {render :partial => "downloadFile"} end 

and make a partial in view folder name with _downloadFile.js.erb and write this line

window.location.href = "<%=@java_url %>" 
like image 193
Asnad Atta Avatar answered Sep 29 '22 22:09

Asnad Atta


You can't download a file to disk from JS. It's a security concern. See the blog post below for a good workaround.

http://johnculviner.com/post/2012/03/22/Ajax-like-feature-rich-file-downloads-with-jQuery-File-Download.aspx

like image 31
kelf Avatar answered Sep 30 '22 00:09

kelf