I have a JSON snippet that I am fetching to save posts to Post
model
It looks like this:
{
"provider_url": "http://twitter.com",
"description": "Four more years. pic.twitter.com/bAJE6Vom",
"title": "Twitter / BarackObama: Four more years. http://t.co/bAJE6Vom",
"author_name": "BarackObama", "height": 532, "thumbnail_width": 150, "width": 800,
"thumbnail_url": "https://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg:thumb",
"author_url": "http://twitter.com/BarackObama", "version": "1.0",
"url": "https://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg:large",
"provider_name": "Twitter", "type": "photo", "thumbnail_height": 150
}
The image being saved is the original photo URL from the provider.
For example: https://pbs.twimg.com/media/A7EiDWcCYAAZT1D.jpg
I want to archive the image into my own Amazon S3 storage using Paperclip if possible.
I also have a Post
column named backup_s3_url
where I want to store my uploaded/duplicated image URL hosted by S3.
I tried to use open-uri
still... But it's still getting the original image URL. I want to directly save the image from URL using paperclip.
def picture_from_url(url)
self.photo = URI.parse(url)
end
But the code above doesn't work, FYI.
Any workarounds will be appreciated.
Send the json image as a base64 encoded string.
On Rails decode this and save to S3 with paperclip.
For my iOS app I send the base64 string to a virtual attribute on the Rails model and use "before_save" to set the real S3 attribute value to the decoded string.
class Media1 < ActiveRecord::Base
before_save :set_custom_photo
attr_accessor :phototmp
has_attached_file :photo,
:styles =>
{ :thumb => '150x150#',
:small => '100x100>',
:large => '600x600>'},
:storage => :s3,
:s3_credentials => "#{Rails.root}/config/s3.yml",
:s3_protocol => "https",
:path => ":class/:id/:basename_:style.:extension",
:url => ":s3_eu_url"
validates_attachment_size :photo, :less_than => 5.megabytes
validates_attachment_content_type :photo, :content_type => ['image/jpeg', 'image/png']
def set_custom_photo
data = StringIO.new(Base64.decode64(self.phototmp))
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = "mapimage.png"
data.content_type = "image/png"
self.photo = data
end
end
Maybe these resources might be helpful:
Uploading from a url with paperclip: https://stackoverflow.com/a/4050758/2463468
Save to s3 with paperclip: https://github.com/thoughtbot/paperclip/wiki/Paperclip-with-Amazon-S3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.