Tôi muốn thực hiện điều tương tự như từ base64 photo and paperclip -Rails, nhưng với Carrierwave. Có ai có thể giải thích cho tôi về việc sử dụng hình ảnh base64 trong Carrierwave không?sử dụng hình ảnh base64 với Carrierwave
5
A
Trả lời
6
class ImageUploader < CarrierWave::Uploader::Base
class FilelessIO < StringIO
attr_accessor :original_filename
attr_accessor :content_type
end
before :cache, :convert_base64
def convert_base64(file)
if file.respond_to?(:original_filename) &&
file.original_filename.match(/^base64:/)
fname = file.original_filename.gsub(/^base64:/, '')
ctype = file.content_type
decoded = Base64.decode64(file.read)
file.file.tempfile.close!
decoded = FilelessIO.new(decoded)
decoded.original_filename = fname
decoded.content_type = ctype
file.__send__ :file=, decoded
end
file
end
1
Câu trả lời được chấp nhận không hiệu quả đối với tôi (v0.9). Dường như là một kiểm tra không thành công trước khi gọi lại bộ nhớ cache.
thi này hoạt động:
class ImageUploader < CarrierWave::Uploader::Base
# Mimick an UploadedFile.
class FilelessIO < StringIO
attr_accessor :original_filename
attr_accessor :content_type
end
# Param must be a hash with to 'base64_contents' and 'filename'.
def cache!(file)
if file.respond_to?(:has_key?) && file.has_key?(:base64_contents) && file.has_key?(:filename)
local_file = FilelessIO.new(Base64.decode64(file[:base64_contents]))
local_file.original_filename = file[:filename]
extension = File.extname(file[:filename])[1..-1]
local_file.content_type = Mime::Type.lookup_by_extension(extension).to_s
super(local_file)
else
super(file)
end
end
end
Làm thế nào để tôi lưu các tập tin thông qua bộ điều khiển? Bạn có một mẫu cho điều này không? – fabian