Chris Mendla
Chris Mendla

Reputation: 1017

Getting ActionController::MissingFile when trying to force a download (vice open) with send_file

I am using rails 4.x with paperclip. I want to ensure that when the user clicks on a link to download a paperclip attachment, the file is downloaded instead of opening up.

The link I was using that would open or save depending on the browser configuration was

<%=  link_to image_tag("save.gif", document.doc_file.url, :target => "_blank"  %>

That link will sometimes open the file instead of downloading.

I set up a method of

helper_method :download

  def download
    @document= Document.find(39)
send_file ("http://localhost:3000/images/39/Medical_Opportunity_EvaluationForm.pdf?1458068410"),
              :filename => @document.doc_file_file_name,
              :type => @document.doc_file_content_type,
              :disposition => 'attachment'
  end

I hardwired the url for testing. I had also tried with send_file ("http://localhost:3000#{@document.doc_file.url}") and send_file (@document.doc_file.url). NEither worked.

My link to that is

<%=  link_to image_tag("save.gif"), download_path(document.id)   %>

routes.rb has

  match 'documents/download/:id' => 'documents#download',via: [:get, :post], :as => 'download'

When I click on the download link, I get an error of

ActionController::MissingFile in DocumentsController#download 
Cannot read file http://localhost:3000/images/39/Medical_Opportunity_EvaluationForm.pdf
Rails.root: C:/Users/cmendla/RubymineProjects/technical_library

Application Trace | Framework Trace | Full Trace 
app/controllers/documents_controller.rb:17:in `download'

If I put the URL into an address bar on a browser, it works. i.e. `http://localhost:3000/images/39/Medical_Opportunity_EvaluationForm.pdf'

Upvotes: 0

Views: 1570

Answers (1)

Matouš Bor&#225;k
Matouš Bor&#225;k

Reputation: 15954

The send_file method accepts the physical location of the file on your server, not public URL. So something like the following should work, depending on where the PDF file actually resides:

send_file "#{Rails.root}/public/images/39/Medical_Opportunity_EvaluationForm.pdf",
          :filename => @document.doc_file_file_name,
          :type => @document.doc_file_content_type,
          :disposition => 'attachment'

If this is a paperclip document, the path method should work:

send_file @document.doc_file.path,
          :filename => @document.doc_file_file_name,
          :type => @document.doc_file_content_type,
          :disposition => 'attachment'

See the docs for more info.

Upvotes: 4

Related Questions