Mar*_*oda 10 base64 ruby-on-rails image paperclip
我有一个带有图像属性的Photo模型.该图像包含从api获得的base64字符串.我需要运行一个after_create回调,我想我可以使用Paperclip将图像保存到回调中的磁盘,因为它可以节省我在公共文件夹中实现文件夹结构并生成缩略图的一些工作.有一个简单的方法吗?
Mar*_*oda 17
要回答我自己的问题,这就是我想出的:
class Photo < ActiveRecord::Base
before_validation :set_image
has_attached_file :image, styles: { thumb: "x100>" }
validates_attachment :image, presence: true, content_type: { content_type: ["image/jpeg", "image/jpg"] }, size: { in: 0..10.megabytes }
def set_image
StringIO.open(Base64.decode64(image_json)) do |data|
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = "file.jpg"
data.content_type = "image/jpeg"
self.image = data
end
end
end
Run Code Online (Sandbox Code Playgroud)
image_json是一个包含实际base64编码图像的文本字段(只是数据部分,例如"/ 9j/4AAQSkZJRg ...")
你的set_image看起来应该是这样的
def set_image
self.update({image_attr: "data:image/jpeg;base64," + image_json[PATH_TO_BASE64_DATA]})
end
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7100 次 |
最近记录: |