How to trigger download with Rails send_data from AJAX post

前端 未结 3 1213
小蘑菇
小蘑菇 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: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 %>"
    

提交回复
热议问题