How to trigger download with Rails send_data from AJAX post How to trigger download with Rails send_data from AJAX post ajax ajax

How to trigger download with Rails send_data from AJAX post


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 %>"


Do not just copy and paste the accepted answer. It is a massive security risk that cannot be understated. Although the technique is clever, delivering a file based on a parameter anybody can enter allows access to any file anybody can imagine is lying around.

Here's an example of a more secure way to use the same technique. It assumes there is a user logged in who has an API token, but you should be able to adapt it to your own scenario.

In the action:

current_user.pending_download = file_namecurrent_user.save!respond_to do |format|  @java_url = "/ajax_download?token=#{current_user.api_token}"  format.js {render :partial => "downloadFile"}end

Create a function in the controller

def ajax_download  if params[:token] == current_user.api_token    send_file "path_to_file/" + current_user.pending_download    current_user.pending_download = ''    current_user.save!  else    redirect_to root_path, notice: "Unauthorized"  endend

Make a partial in view folder name with _downloadFile.js.erb

window.location.href = "<%=@java_url %>"

And of course you will need a route that points to /ajax_download in routes.rb

get 'ajax_download', to: 'controller#ajax_download'