问题
I've tried a million different tutorials on the internet for how to upload a Base64 image from my iOS application to my rails app. It seems that no matter how I format the request it just won't get accepted.
Does anyone know definitively how to upload a Base64 image to paperclip?
I tried sending the param as JSON
{ "thumbnail_image": "base64_data..." }
I also tried appending the data url
{ "thumbnail_image": "data:image/jpeg;base64,alkwdjlaks..." }
I tried sending a JSON object with and without data url
{ "thumbnail_image": { "filename": "thumbnail.jpg", "file_data": "base64_data...", "content_type": "image/jpeg" } }
I consistently get these Paperclip::NoHandlerError
s and then it dumps a giant blob of data into my log.
回答1:
Your Base64 string seems to be fine. You can always check that here
So the problem is probably on the Rails side. Check that the string you receive is exactly the same like the one you are sending.
With Paperclip 4.2.1 I managed to save Base64 GIF file that way:
Having:
class Thing
has_attached_file :image
and POST attributes:
{
"thumbnail_data:" "data:image/gif;base64,iVBORw0KGgo..."
}
All you have to do is to find proper adapter and specify original_filename. So for controller that would be:
def create
image = Paperclip.io_adapters.for(params[:thumbnail_data])
image.original_filename = "something.gif"
Thing.create!(image: image)
...
end
AFAIK Paperclip made it easier to save base64 from version 3.5.0.
Hope that helps!
回答2:
This is how I have done it in the past and it is basically a brute force approach, not sure if paperclip has added better support in recent versions, but this should work
class FooBar < ActiveRecord::Base
has_attached_file :thumbnail_image
validates_attachment_content_type :thumbnail_image,
content_type: %w(image/jpeg image/jpg image/png image/gif),
message: "is not gif, png, jpg, or jpeg."
attr_accessor :base64_thumbnail_image
# call this explicitly from the controller or in an after_save callback
# after setting the base64_thumbnail_image attribute
def save_base64_thumbnail_image
if base64_thumbnail_image.present?
file_path = "tmp/foo_bar_thumbnail_image_#{self.id}.png"
File.open(file_path, 'wb') { |f| f.write(Base64.decode64(base64_thumbnail_image)) }
# set the paperclip attribute and let it do its thing
self.thumbnail_image = File.new(file_path, 'r')
end
end
end
# params should be base64_thumbnail_image, not thumbnail_image in this case
来源:https://stackoverflow.com/questions/27234065/how-to-upload-a-base-64-image-to-rails-paperclip