How to trigger download with Rails send_data from AJAX post

前端 未结 3 1210
小蘑菇
小蘑菇 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:36

    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

    0 讨论(0)
  • 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'
    
    0 讨论(0)
  • 2020-12-08 15:52

    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 %>"
    
    0 讨论(0)
提交回复
热议问题