【问题标题】:Cannot read file with send_file function in Rails 3无法在 Rails 3 中使用 send_file 函数读取文件
【发布时间】:2012-01-12 20:52:46
【问题描述】:

我正在使用的代码:

在视图文件中:

 <%= 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、视频)。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 sendfile


    【解决方案1】:

    只需按路径更改 URL 方法:

    send_file  @image.attachment.path # this is the right way!.
    

    【讨论】:

      【解决方案2】:

      我不知道你是怎么保存图片附件url的,但是一般来说,文件名应该是这样的:

      /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” .

      对于文件 url,它可能类似于:http://example.com/xxx?dddd,哪个字符“?”拆分路径和参数。字符串“dddd”是请求url路径时的参数,它不是路径或文件名的一部分。参数只支持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】:

        问题是:

        我正在使用

         @image = Image.find(params[:id])
         send_file "#{RAILS_ROOT}/public"  + @image.attachment.url
        

        应该是

         @image = Image.find(params[:id])
         send_file  @image.attachment.path
        

        PS:确保您验证图像/记录存在。

        【讨论】:

        • 如果你使用brakeman分析代码,那么它会显示错误为MODEL属性用作文件名。只是运行刹车。它被认为是 send_file Image.find(params[:id]).uploaded_file.path
        【解决方案4】:

        这个?1320582022 是否属于文件名?我也不确定文件名中的空格,也许它们需要转义。

        【讨论】:

        • 屏幕截图 2011-11-04 at 3.14.03 PM.png 是文件名,而 ?1320582022 即将到来,因为我在开发模式下遇到问题..
        猜你喜欢
        • 2017-01-01
        • 2017-01-07
        • 2013-02-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多