How to update/rename a carrierwave uploaded file?

后端 未结 6 1331
我在风中等你
我在风中等你 2021-02-04 20:30

I cant figure out how to update/rename a file uploaded/managed with Carrierwave-mongoid in rails 3.2.6. I want to rename the file in the db as well as on the filesystem.

<
6条回答
  •  离开以前
    2021-02-04 20:55

    The most efficient way to do this is to just move the existing S3 object (assuming your storage layer is S3):

    def rename(new_name)
      bucket_name = "yourapp-#{Rails.env}"
      resource = Aws::S3::Resource.new
      bucket = resource.bucket(bucket_name)
      object = bucket.object(path)
      new_filename = "#{new_name}#{File.extname(path)}"
      new_path = File.join(File.dirname(path), new_filename)
      object.move_to(bucket: bucket_name, key: new_path)
    
      model.update_column(mounted_as, new_filename)
      model.reload
    
      # Now call `recreate_versions!(*versions.keys)`
      # if you want versions updated. Explicitly passing
      # versions will prevent the base version getting
      # reuploaded.
    
      model
    end
    

    This is using the aws-sdk-s3 gem.

提交回复
热议问题