How to specify a prefix when uploading to S3 using activestorage's direct upload?

后端 未结 4 812
渐次进展
渐次进展 2020-12-03 05:42

With a standard S3 configuration:

AWS_ACCESS_KEY_ID:        [AWS ID]
AWS_BUCKET:               [bucket name]
AWS_REGION:               [region]
AWS_SECRET_AC         


        
4条回答
  •  [愿得一人]
    2020-12-03 06:19

    The above solution will still give IntegrityError, need to use File.open(file). Thank Though for idea.

    class History < ApplicationRecord
      has_one_attached :gs_history_file
    
      def attach(file) # method for attaching in the model
        blob_key = destination_pathname(file)
        blob = ActiveStorage::Blob.find_by(key: blob_key.to_s)
        unless blob
          blob = ActiveStorage::Blob.new.tap do |blob|
            blob.filename = blob_key.to_s
            blob.key = blob_key
            #blob.byte_size = 123123
            #blob.checksum = Time.new.strftime("%Y%m%d-") + Faker::Alphanumeric.alpha(6)
            blob.upload File.open(file)
            blob.save!
          end
        end
    
        # Attach method from ActiveStorage
        self.gs_history_file.attach blob
      end
    
      def destination_pathname(file)
        "testing/filename-#{Time.now}.xlsx"
      end
    end
    

提交回复
热议问题