使用Paperclip下载附加的图片

3

有没有办法让用户使用Paperclip下载附加的图片?

我只是创建了一个链接,如下所示:

link_to 'imagename', image.attachment.url

但是这会让浏览器打开图片。我想让浏览器询问用户是否保存图片。有没有办法做到这一点?


以前从来没有做过这个,但这篇文章可能会有所帮助:http://therailsway.com/2009/2/22/file-downloads-done-right - iwasrobbed
1
请精确复制此问题的链接:https://dev59.com/WWw15IYBdhLWcg3wMpEY - vinceh
2个回答

3

说到发送文件,您可以在这里找到所有信息:http://api.rubyonrails.org/classes/ActionController/Streaming.html 其中最重要的有:

简单下载:

send_file '/path/to.zip'

在浏览器中显示JPEG图像:

send_file '/path/to.jpeg', :type => 'image/jpeg', :disposition => 'inline'

在浏览器中显示404页面:
send_file '/path/to/404.html', :type => 'text/html; charset=utf-8', :status => 404

要使用其中一种选项,您需要在控制器中创建一个新的操作,如下所示:

要使用其中一种选项,您需要在控制器中创建一个新的操作,如下所示:

class SomeController < ApplicationController
  def download_file
    send_file image.attachment.path
  end
end

1

这里有一个简单的解决方案,使用HTML5的下载属性

<%= link_to image.name, image.attachment.url, download: image.attachment.original_filename %>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接