【问题标题】:Carrierwave uncompress RAR file after uploadCarrierwave 上传后解压 RAR 文件
【发布时间】:2015-02-10 00:52:00
【问题描述】:

我实际上正在寻找的建议不仅仅是关于如何在上传后解压缩 RAR/ZIP 文件同时保持最大数据完整性率的纯编码答案。

这是我的问题:我的应用程序的用户正在上传由 Adob​​e Edge 生成的文件(我们将其用于动画广告),这些文件是 RAR 格式的。要上传文件,这真的很简单。这是我的上传者:

class MediaUploader < CarrierWave::Uploader::Base
  storage :file

  def store_dir
    "uploads/#{ model.class.to_s.underscore }/#{ mounted_as }/#{ ScatterSwap.hash(model.id) }"
  end

  def extension_white_list
    %w(jpg jpeg gif png rar zip)
  end

  def filename
    "#{ secure_token }.#{ file.extension }" if original_filename.present?
  end

  protected

  def secure_token
    var = :"@#{ mounted_as }_secure_token"
    model.instance_variable_get(var) or model.instance_variable_set(var, SecureRandom.uuid)
  end
end

现在,就我而言,RAR 文件实际上并不是我将要使用的文件。我需要的是档案中包含的文件。这些文件通常看起来像这样:

- edge_includes
|
- images
|
- js
|
| ADS_1234_988x160_edge.js
| ADS_1234_988x160_edgeActions.js
| ADS_1234_988x160.an
| ADS_1234_988x160.html

从上面的例子中,我需要在数据库中存储对ADS_1234_988x160.html文件的引用。

为此,我打算使用 Carrierwave 回调来:

after :store, :uncompress_and_update_reference

def uncompress_and_update_reference(file)
  # uncompress and update reference
end
  • 解压缩存档(可能使用rubyzip
  • 获取ADS_1234_988x160.html的路径
  • 更新数据库内的引用

有没有更好的处理方法?如何处理故障或网络错误?欢迎任何想法。

【问题讨论】:

    标签: ruby-on-rails upload carrierwave rar compression


    【解决方案1】:

    我遇到了类似的问题:zip 已上传,但不应存储,只能存储解压缩的内容。我通过实现专用存储解决了这个问题。比如:

    class MyStorage
      class App < CarrierWave::Storage::Abstract
        def store!(file)
          # invoked when file is moved from cache into store
          # unzip and update db here
        end
    
        def retrieve!(identifier)
          MyZipFile.new(identifier)
        end
      end
    end
    
    class MyZipFile
      def initialize(identifier)
        @identifier = identifier
      end
    
      def path
        file.path
      end
    
      def delete
        # delete unzipped files
      end
    
      def file
        @file ||= zip_file
      end
    
      def zip_file
        # create zip file somewhere in tmp dir
      end
    end
    
    # in uploader file
    storage MyStorage
    storage :my_storage
    

    如果使用了符号,则需要在carrierwave config中定义:

    CarrierWave.configure do |config|
      config.storage_engines.merge!(my_storage: 'MyStorage')
    end
    

    【讨论】:

      猜你喜欢
      • 2020-09-18
      • 1970-01-01
      • 2012-03-16
      • 1970-01-01
      • 2015-11-01
      • 2016-10-05
      • 2021-01-15
      • 2015-06-23
      • 1970-01-01
      相关资源
      最近更新 更多