How to trigger download with Rails send_data from AJAX post

前端 未结 3 1212
小蘑菇
小蘑菇 2020-12-08 15:19

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 callba

3条回答
  •  旧巷少年郎
    2020-12-08 15:39

    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_name
    current_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"
      end
    end
    

    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'
    

提交回复
热议问题