Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby On Rails: send_file through jquery/ajax request

I am having trouble downloading files from my rails server through ajax:

I have a show action in my downloads controller that calls send_file if a parameter is passed to the show action.

I then have a page where there is a select dropdown that shows a list of files that are on the server. 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.

Looking at my server logs, it seems that the ajax request is working and it says:

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. What am I doing wrong?

--

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
like image 341
rhfannnn Avatar asked Feb 20 '23 19:02

rhfannnn


1 Answers

I had the same problem, well kind of, but instead of using JS click function, I used rails link tag.

Originally, in my view I had a link_to tag with remote: true (wich produces the ajax call)

The link aimed an action that produced a PDF. The PDF was generated (with prawn and thinreports) and sent, but the download dialog did not popup.

So I remove the remote: true and add a target: '_self', so it ended up like this (I am using 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?

like image 106
OfficeYA Virtual Offices Avatar answered Mar 03 '23 23:03

OfficeYA Virtual Offices