Carrierwave gem安全文件路径无法读取文件路径错误

时间:2015-08-24 06:29:11

标签: ruby-on-rails ruby carrierwave image-uploading

我试图遵循载波中的“安全上传”,这有点令人困惑,因为我已经自定义了文件路径。当我尝试运行应用程序时,出现“无法读取文件”错误。

这是路线:

match "/upload_files/:tenant_id/:model/:mount_as/:id/:basename.:extension" => "documents#download",via: [:get, :post] 

class ImageUploader < CarrierWave::Uploader::Base
  def store_dir
"upload_files/#{model.tenant_id}/#model.class.to_s.underscore}/#mounted_as}/#{model.id}"

端 端

carrierwave.rb初始化程序:

CarrierWave.configure do |config|
  config.permissions = 0600
  config.directory_permissions = 0700
  config.root = Rails.root
end

文件控制器:`

def download
  path = request.fullpath
  send_file path
end

得到了错误

ActionController :: DocumentsController中的MissingFile #download 无法读取文件/upload_files/1/hoshin_attachment/image/3/support3_HoshinUserStatusReports_08_14_2015.pdf 请帮我找到解决方案

1 个答案:

答案 0 :(得分:0)

CarrierWave似乎使用 root 变量和上传者store_dir来计算路径。 我想将我的文件存储在Rails.root下的私人文件夹中。 设置根目录:

# config/initializers/carrierwave.rb

# Uploader settings
CarrierWave.root = Rails.root.to_s
CarrierWave::Uploader::Base.root = Rails.root.to_s

设置store_dir:

# In your uploader class definition
def store_dir
  "private/your_app/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"
end

由于文件不在公用文件夹中,因此它们需要控制器中的操作才能显示和下载。让我们假设上传文件的列名为 uploaded_file

# In some controller
# you have to ensure @document initialize with a before_action filter


def show_file
  send_file @document.unsigned_file.path,
            filename: @document.uploaded_file_identifier,
            disposition: :inline,
            type: @document.uploaded_file.content_type
end

def download_file
  send_file @document.unsigned_file.path,
            filename: @document.uploaded_file_identifier,
            disposition: :attachment,
            type: @document.uploaded_file.content_type
end