Rails: How to download a previously uploaded document?

10,143

Solution 1

I don't use Carrierwave but I guess it's similar to Paperclip.

Therefore you should be able to use something like this

 link_to 'Download file', user.file.url

This is assuming you have a user instantiated object from a Model with a 'file' carrierwave attribute. Replace this with your attribute name.

Solution 2

You can use the send_file method for this. Which could look like:

class MyController
  def download_file
    @model = MyModel.find(params[:id])
    send_file(@model.file.path,
          :filename => @model.file.name,
          :type => @model.file.content_type,
          :disposition => 'attachment',
          :url_based_filename => true)
  end
end

Check the apidock link for more examples.

Share:
10,143
Barbared
Author by

Barbared

Ruby Developer

Updated on June 04, 2022

Comments

  • Barbared
    Barbared almost 2 years

    I need my user to upload documents such ad pdf and txt on their profile. And I did that using Carrierwave, so I have a list of documents with titles and urls.

    But how can I make other users download those files? Do I have to use a gem or is there something native I don't even know since I am very new to rails?

    Thanks

    EDIT:

    society.rb

    class Society < ActiveRecord::Base
      ...
      has_many :documents, :dependent => :destroy
    end
    

    document.rb

    class Document < ActiveRecord::Base
      belongs_to :society    
      mount_uploader :url, DocumentUploader    
    end
    

    And then this in the view I want to download files:

      <% @society.documents.each do |doc| %>
        <%= link_to "Download it", doc.url %>    //url is the column name of the saved url
      <% end %>