【问题标题】:Carrierwave gem Secure File Path Cannot read filepath errorCarrierwave gem 安全文件路径无法读取文件路径错误
【发布时间】:2015-11-17 11:43:30
【问题描述】:

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

路线如下:

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::MissingFile in DocumentsController#download 无法读取文件/upload_files/1/hoshin_attachment/image/3/support3_HoshinUserStatusReports_08_14_2015.pdf 请帮助我找到解决方案

【问题讨论】:

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


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 2012-07-02
      • 1970-01-01
      • 1970-01-01
      • 2018-12-21
      • 2017-02-18
      相关资源
      最近更新 更多