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

后端 未结 4 813
渐次进展
渐次进展 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:24

    Thank you, Sonia, for your answer.

    I tried your solution and it works great, but I encountered problems with overwriting attachments. I often got IntegrityError while doing it. I think, that this and checksum handling may be the reason why the Rails core team don't want to add passing pathname feature. It would require changing the entire logic of the upload method.

    ActiveStorage::Attached#create_from_blob method, could also accepts an ActiveStorage::Blob object. So I tried a different approach:

    1. Create a Blob manually with a key that represents desired file structure and uploaded attachment.
    2. Attach created Blob with the ActiveStorage method.

    In my usage, the solution was something like that:

    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.basename.to_s
          blob.key = blob_key
          blob.upload file
          blob.save!
        end
      end
    
      # Attach method from ActiveStorage
      self.file.attach blob
    end
    

    Thanks to passing a full pathname to Blob's key I received desired file structure on a server.

提交回复
热议问题