我正在使用的代码:
在视图文件中:
<%= link_to "Download", download_image_path(image) %>
在控制器中:
def download
@image = Image.find(params[:id])
send_file "#{RAILS_ROOT}/public" + @image.attachment.url
end
我收到错误:
Cannot read file /Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022
PS:仔细检查,文件存在。服务器上的相同问题,适用于所有相应控制器中的所有文件(图像,pdf,视频)。
答案 0 :(得分:16)
问题是:
我正在使用
@image = Image.find(params[:id])
send_file "#{RAILS_ROOT}/public" + @image.attachment.url
应该是
@image = Image.find(params[:id])
send_file @image.attachment.path
PS:确保验证图像/记录是否存在。
答案 1 :(得分:3)
只需按路径更改网址方式:
send_file @image.attachment.path # this is the right way!.
答案 2 :(得分:1)
我不知道你如何保存图片附件网址,但一般来说,文件名应该是这样的:
/Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png
注意它最后没有“?xxxxx”。
您可以检查文件系统,文件名是“Screen Shot 2011-11-04 at 3.14.03 PM.png”还是“Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022”
对于文件网址,它可能类似于:http://example.com/xxx?dddd,字符“?”拆分路径和参数。字符串“dddd”是请求url路径时的参数,它不是路径或文件名的一部分。参数仅支持url,而不支持本地文件名。
所以,我认为您需要检查保存图像附件网址的代码,这需要排除参数和文件名。并确保名称与保存到磁盘的文件完全相同。
您可以尝试直接打开文件irb并检查输出:
>>> irb
irb> f = open('/Users/mohit/projects/my_app/public/system/attachments/4/original/Screen Shot 2011-11-04 at 3.14.03 PM.png?1320582022')
其他人,尝试在send_file中找到错误位置,并检查文件名。
我仍然无法确定问题究竟是什么,只是一些建议。
答案 3 :(得分:0)
这个?1320582022
是否属于文件名?我不确定文件名中的空格,也许它们需要被转义。