carrierwave: point to existing image

2019-06-22 15:40发布

In my rails app, I'm using Carrierwave to upload images on Amazon S3. I'd like to point to existing Amazon S3 images without having to re-upload the image. For example, if I have an existing Amazon S3 image at http://test.s3.amazonaws.com/image/path/0001/image.jpg, can I update an image's path to point to this image? I don't want to use the remote upload option because I really just want to use the same exact image that's already there (but save it in my record's "path" attribute).

In the console, I've tried:

image.update_attributes(:path=> "http://test.s3.amazonaws.com/image/path/0001/image.jpg")

but this fails to override the image's path.

4条回答
ら.Afraid
2楼-- · 2019-06-22 16:08

I found that you can actually do this, for example if your mount_uploader is :path, then:

image.remote_path_url = "http://test.s3.amazonaws.com/image/path/0001/image.jpg"
image.save
查看更多
唯我独甜
3楼-- · 2019-06-22 16:15

Chiming in, better late than never! Caveat: This is for rails 4, and I am testing on rails 4.1 only at the moment.

This is harder than it should be, methinks! The reason this was absolutely crucial to me was that I am attaching 100MB+ MP3 files, which I cannot receive on my host, due to CloudFlare SSL limitations (and common sense). Fortunately, AWS supports preauthorized uploads, and I got carrierwave to do the right thing for me:

Step 1: get carrierwave to tell me where it would store a file if it could:

 m.raw_write_attribute('file','file.mp3');
 url = m.file.url
 signed = aws_presigned_url(url)

raw_write_attribute does not save anything, it just bypasses carrierwave when setting the value. This makes the object act as if it read 'file.mp3' out of the database. Then you can ask Carrierwave "where the file lives". I then upload the file directly from the client to S3. When that's done, I make another API call to Rails, which performs the following code:

 m.raw_write_attribute('file','file.mp3');
 m.update_attribute('file','file.mp3');

These two paired get around Carrierwave. The first makes carrierwave think that the 'file' column is set to 'file.mp3', the second explicitly tells rails to persist 'file.mp3' to the DB. Because of the raw_write_attribute call, Carrierwave allows the second through un-changed.

查看更多
贼婆χ
4楼-- · 2019-06-22 16:18

I am a bit late to the party, but you can use Active Record's raw_write_attribute method something like:

@image.raw_write_attribute(:path, "http://test.s3.amazonaws.com/image/path/0001/image.jpg")

查看更多
爷、活的狠高调
5楼-- · 2019-06-22 16:23

In my case update_column and update_columns worked great:

model.update_columns file_1: 'filename.txt'

Update column is with comma:

model.update_column :file_1, 'filename.txt'

This will not run any callback and set column to filename.txt.

When I do model.file_1.url I get the right S3 URL.

查看更多
登录 后发表回答