-
-
Save WizardOfOgz/1012107 to your computer and use it in GitHub Desktop.
class Avatar < ActiveRecord::Base | |
attr_accessor :content_type, :original_filename, :image_data | |
before_save :decode_base64_image | |
has_attached_file :image, | |
PAPERCLIP_CONFIG.merge( | |
:styles => { | |
:thumb => '32x32#', | |
:medium => '64x64#', | |
:large => '256x256#' | |
}) | |
protected | |
def decode_base64_image | |
if image_data && content_type && original_filename | |
decoded_data = Base64.decode64(image_data) | |
data = StringIO.new(decoded_data) | |
data.class_eval do | |
attr_accessor :content_type, :original_filename | |
end | |
data.content_type = content_type | |
data.original_filename = File.basename(original_filename) | |
self.image = data | |
end | |
end | |
end |
Questioned answered here:
http://stackoverflow.com/questions/29930430/upload-base64-image-with-paperclip-rails-4
Thanks @delvarworld and @pjar - really helpful. I have also found that you can just include the original filename in the params too and Paperclip will automatically include it in the image processing and use it for the newly generated image.
e.g.
{ "model": { "image": "data:image/png;base64,iVBORw0KGgo...", "image_file_name": "file.png" } }
This is particularly useful if you are POSTing the base64 encoded image to a Rails API via a web app - as you can get the filename of the image via the FileReader HTML5 API and submit it in your POST request, like above. Hope this helps someone.
This is no longer included by default in v5. You have to register the DataUri IO adapter, see more here: https://github.com/thoughtbot/paperclip#io-adapters
You should still pass an image_file_name
like above, though.
@sarink I've include Paperclip::DataUriAdapter.register
in paperclip.rb and still don't upload the image
This is so easy!
If you're on paperclip 5.1.0 you don't need to use the Paperclip::DataUriAdapter.register
, it's still included by default. I believe they only changed this with 5.2.0
Here it is saving only original format, any suggestion?
Paperclip 5.0
Hi,
I am attempting to implement @pjar 's code into my controller but am getting stuck on
Thing.create(image: image)
. I don't think I understand it, and therefore am failing to implement his solution in my code below: