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

前端 未结 5 1225
我寻月下人不归
我寻月下人不归 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条回答
  •  -上瘾入骨i
    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 %>
    

提交回复
热议问题