简体   繁体   English

Ruby On Rails:send_file通过jquery / ajax请求

[英]Ruby On Rails: send_file through jquery/ajax request

I am having trouble downloading files from my rails server through ajax: 我无法通过ajax从rails服务器下载文件:

I have a show action in my downloads controller that calls send_file if a parameter is passed to the show action. 我的下载控制器中有一个show动作,如果参数传递给show动作,则调用send_file

I then have a page where there is a select dropdown that shows a list of files that are on the server. 然后我有一个页面,其中有一个select下拉列表,显示服务器上的文件列表。 When I select a value and click the download button, it issues an ajax request that sends a GET request which is processed by my downloads controller. 当我选择一个值并单击下载按钮时,它会发出一个ajax请求,该请求发送由我的下载控制器处理的GET请求。

Looking at my server logs, it seems that the ajax request is working and it says: 查看我的服务器日志,似乎ajax请求正在运行,它说:

Started GET "/download?file=test.txt" for 127.0.0.1 at 2012-07-19 15:13:41 -0700
Processing by DownloadsController#show as HTML
  Parameters: {"file"=>"test.txt"}
Sent file /Users/Admin/Documents/rails_projects/test/public/data/test.txt (0.1ms)
Completed 200 OK in 0ms (ActiveRecord: 0.0ms)

However nothing is actually downloaded. 但实际上并未下载任何内容 When I actually visit the show page manually, the file is actually downloaded. 当我实际手动访问show页面时,实际上下载了该文件。 What am I doing wrong? 我究竟做错了什么?

-- -

Javascript 使用Javascript

 <script type="text/javascript">
    $(function() {
      $('#button').click(function() {
        var s = $("select#dropdown_select").val();
               $.ajax({
                      type: 'GET',
                      url: 'http://localhost:3000/download?file=' + s,
                      dataType: "HTML"
                      });
      })
    });
  </script>

Downloads Controller 下载控制器

def show

    filename = params[:dl]

    if(filename.nil? == false)

    path = Rails.root.join('public/data', filename)
    send_file path, :x_sendfile => true

    end
end

I had the same problem, well kind of, but instead of using JS click function, I used rails link tag. 我有同样的问题,很好,但不使用JS点击功能,我使用rails link标签。

Originally, in my view I had a link_to tag with remote: true (wich produces the ajax call) 最初,在我看来,我有一个带有remote: truelink_to标签(wich产生ajax调用)

The link aimed an action that produced a PDF. 该链接旨在生成PDF的操作。 The PDF was generated (with prawn and thinreports) and sent, but the download dialog did not popup. PDF已生成(使用prawn和thinreports)并已发送,但下载对话框未弹出。

So I remove the remote: true and add a target: '_self' , so it ended up like this (I am using haml) 所以我删除了remote: true并添加了一个target: '_self' ,所以最终就像这样(我正在使用haml)

!= link_to image_tag( 'print.png' ) + (I18n.t :buttons)[:comments][:print],
    customer_comment_path(@address_book),
    { target: '_self' }

And it worked just fine. 它运作得很好。

Why don't you try to rewrite the code using Rail's link tags? 为什么不尝试使用Rail的link标记重写代码?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM