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?
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.
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.
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.
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.
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:
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.
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 %>"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With