0

我使用 Paperclip 4.0.2 并在我的应用程序中上传图片。

所以我的 Document 模型有一个名为 attach_fileattachment

附件的样式很少,比如说:medium, :thumb, :facebook

在我的模型中,我停止了样式处理,并将其提取到后台作业中。

class Document < ActiveRecord::Base
# stop paperclip styles generation    
before_post_process
  false
end

但是 :original 样式文件仍然上传!

我想知道是否可以停止这种行为并从远程目录复制 :original/filename.jpg 中的文件我的目标是使用已通过 jQuery File upload 上传到 S3 /temp/ 目录中的文件, 并将其复制到 Paperclip 需要它生成其他样式的目录。

预先感谢您的帮助!

4

1 回答 1

0

新答案

回形针附件通过flush_writes一种方法上传,出于您的目的,该方法是Paperclip::Storage::S3模块的一部分。负责上传的行是:

s3_object(style).write(file, write_options)

因此,通过 monkey_patch,您可以将其更改为:

s3_object(style).write(file, write_options) unless style.to_s == "original" and @queued_for_write[:your_processed_style].present?

编辑:这将通过创建以下文件来完成: config/initializers/decorators/paperclip.rb

Paperclip::Storage::S3.class_eval do
  def flush_writes #:nodoc:
    @queued_for_write.each do |style, file|
    retries = 0
      begin
        log("saving #{path(style)}")
        acl = @s3_permissions[style] || @s3_permissions[:default]
        acl = acl.call(self, style) if acl.respond_to?(:call)
        write_options = {
          :content_type => file.content_type,
          :acl => acl
        }

        # add storage class for this style if defined
        storage_class = s3_storage_class(style)
        write_options.merge!(:storage_class => storage_class) if storage_class

        if @s3_server_side_encryption
          write_options[:server_side_encryption] = @s3_server_side_encryption
        end

        style_specific_options = styles[style]

        if style_specific_options
          merge_s3_headers( style_specific_options[:s3_headers], @s3_headers, @s3_metadata) if style_specific_options[:s3_headers]
          @s3_metadata.merge!(style_specific_options[:s3_metadata]) if style_specific_options[:s3_metadata]
        end

        write_options[:metadata] = @s3_metadata unless @s3_metadata.empty?
        write_options.merge!(@s3_headers)

        s3_object(style).write(file, write_options) unless style.to_s == "original" and @queued_for_write[:your_processed_style].present?
      rescue AWS::S3::Errors::NoSuchBucket
        create_bucket
        retry
      rescue AWS::S3::Errors::SlowDown
        retries += 1
        if retries <= 5
          sleep((2 ** retries) * 0.5)
          retry
        else
          raise
        end
      ensure
        file.rewind
      end
    end
    after_flush_writes # allows attachment to clean up temp files
    @queued_for_write = {}
  end
end

现在原件没有上传。然后,如果您希望将原件转移到其适当的最终位置(如果直接上传到 s3),则可以在模型中添加一些行,例如我在下面的原始答案中的行。

原答案

也许像这样放置在使用 after_create 回调执行的模型中:

    paperclip_file_path = "relative/final/destination/file.jpg"
    s3.buckets[BUCKET_NAME].objects[paperclip_file_path].copy_from(relative/temp/location/file.jpg)

感谢https://github.com/uberllama

于 2014-08-30T17:46:01.860 回答