【问题标题】:Rails 3 app + paperclip gem + production mode = download of empty filesRails 3 app + 回形针 gem + 生产模式 = 下载空文件
【发布时间】:2011-06-07 21:54:25
【问题描述】:

我已经为 Rails 3 应用程序安装了回形针 gem。在开发模式下一切正常。但是,在生产模式下运行时,如果我上传一个文件然后尝试再次下载它,它会下载一个具有正确名称和扩展名的文件,但它是一个空文件。在服务器上查看时,文件确实被上传并且位于正确的目录中。 (我的应用程序根目录中有一个“上传”文件夹。)

有人遇到过这种情况吗?

我的模特:

# app/models/document.rb
class Document < ActiveRecord::Base  
  belongs_to :kase  

  has_attached_file :document, :path => (Rails.root + "uploads/:class/:kase_id/:id").to_s, :url => ":class/:id"

  validates_attachment_presence :document
  validates_attachment_content_type :document, :content_type => [
    'application/pdf',
    'image/png',
    'image/jpeg',
    'image/pjpeg',
    'text/plain'
  ]
end

我的控制器:

# app/controllers/documents_controller.rb
class DocumentsController < ApplicationController
  respond_to :html

  before_filter :initialize_kase # Sets the @kase instance

  def show
    @document = @kase.documents.find(params[:id])
    send_file @document.document.path, :filename => @document.document_file_name, :content_type => @document.document_content_type
  end    
end

还有我的初始化程序(设置上面 has_attached_file 中使用的 :kase_id 占位符:

# config/initializers/paperclip.rb
Paperclip.interpolates('kase_id') do |attachment, style|
  "kases/#{attachment.instance.kase.id.to_s}"
end

我可能还应该提到,我作为嵌套控制器 (/kases/XX/documents/XX) 访问它。不知道有没有效果...

【问题讨论】:

  • 你能发布你的上传器的配置并描述你正在使用的服务器吗?
  • 具体来说,我们需要您的型号代码和下载文件的控制器代码。我以前遇到过这个问题并解决了。
  • 很抱歉。我必须先运行才能添加代码。我更新了 OP。

标签: ruby-on-rails paperclip production-environment


【解决方案1】:

如果您使用的是 Apache 和Passenger,(也可能是其他服务器)并且有一行:

config.action_dispatch.x_sendfile_header = "X-Sendfile"

在您的 production.rb 环境文件中,您有两个选择:

  1. 安装 apache 模块 mod-xsendfile
  2. 注释掉该行,让 Rails 发送文件而不是 Apache,就像在开发模式下一样。

【讨论】:

  • 我最终在 config/environments/production.rb 中注释掉了该行,它似乎正在工作。谢谢!
【解决方案2】:

您是否在每次将应用部署到生产环境时都保留上传目录?假设您使用 capistrano(或类似的)进行部署,每次部署时,您可能会在新部署的发布目录中创建一个新的上传目录。在这种情况下,之前上传的文件驻留在较旧的已部署版本中(如果您没有删除这些文件),您的应用将无法再访问这些文件。

你想创建例如shared/uploads 在每次部署时符号链接到您的应用程序的目录。

【讨论】:

  • 我目前没有使用 capistrano,但是当我到达那个点时,这是非常好的信息。感谢您的提醒。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-11-19
  • 1970-01-01
  • 2014-09-03
  • 2011-07-16
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
相关资源
最近更新 更多