Rails 'link_to' to Download An Image Immediately Instead of Opening it in the Browser

前端 未结 5 1222
我寻月下人不归
我寻月下人不归 2020-12-31 02:11

I have a link_to Rails helper that downloads a wallpaper when clicked. But the image is loading in the browser instead of being downloaded immediately.

<%         


        
相关标签:
5条回答
  • 2020-12-31 02:38

    Instead of putting the link of the image in your tag, you can handle it in your controller. And then in your controller you can do something like

    send_file @download.wallpapers[1].wallpaper.url, :type => 'image/jpeg', :disposition => 'attachment'
    

    Read this

    0 讨论(0)
  • 2020-12-31 02:45

    Generally, the cleanest way to do this is to set the appropriate header when sending the image:

    Content-Disposition: attachment; filename=&lt;file name.ext&gt;
    

    The send_file method will allow you to set this header appropriately if you're serving the file from the filesystem:

    http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_file

    If the file is stored in your database, you can use send_data instead:

    http://api.rubyonrails.org/classes/ActionController/Streaming.html#method-i-send_data

    0 讨论(0)
  • 2020-12-31 02:46

    Here's a simple solution using the HTML5 download attribute with paperclip

    <%= link_to item.name, item.asset.url, download: item.asset.original_filename %>
    
    0 讨论(0)
  • 2020-12-31 02:47

    There is an easier way to do this with the HTML5 download attribute.

    <%= link_to 'Download existing avatar', @user.avatar(:original), download: "User_#{@user.id}_avatar" %>
    
    0 讨论(0)
  • 2020-12-31 03:02

    Rails 3 / 4:

    in routes:

    get "home/download_pdf"
    

    in controller:

    def download_pdf
      send_file(
        "#{Rails.root}/public/your_file.pdf",
        filename: "your_custom_file_name.pdf",
        type: "application/pdf"
      )
    end
    

    in view:

    <%= link_to 'Download PDF', home_download_pdf_url %>
    
    0 讨论(0)
提交回复
热议问题