How to Create Download Link

前端 未结 3 1597
粉色の甜心
粉色の甜心 2021-02-06 01:13

What\'s the best way to create a download link? Is there a better way than the following?

I was thinking of using link_to \"Download\", :controller => ..., :act

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-06 01:35

    I add the download action as a restful route in a resources block. Here's typical code for me:

    routes.rb

      resources :things do
        member do
          get :download
        end
      end    
    

    model:

      has_attached_file :document,
        :path => ':rails_root/assets/documents/:id/:basename.:extension'
      attr_protected :document_file_name, :document_content_type, :document_file_size
    

    controller:

      def download
        send_file @thing.document.path, :type => 'application/pdf', :filename => @thing.permalink
      end
    

    view:

      <%= link_to 'Download', download_thing_path(@thing) %>
    

    This keeps the user on the same page, and just initiates the download with my suggested name (I use permalink).

    What do you mean by dynamically generated? Are they uploaded by you or created by your application on the fly?

提交回复
热议问题