[英]Rails Carrierwave Base64 image upload
使用Carrierwave將圖像從客戶端上傳到Rails后端的最佳方法是什么? 現在我們的iOS開發人員將文件作為base64發送,因此請求如下:
"image_data"=>"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAHqADAAQAAAABAAAAHgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAeAB4DAREAAhEBAxEB/8QAHwAAAQUBAQE....
所以,我的問題實際上是兩個問題。 我應該告訴他發送不同的文件格式嗎? 如果base64是發送這些文件的正確方法,那么我如何在carrierwave中處理它們?
我認為一種解決方案可以是將解碼后的數據保存到文件中,然后將此文件分配給已安裝的上傳器。 然后擺脫那個文件。
另一個(內存中)解決方案可以是這個:
# define class that extends IO with methods that are required by carrierwave
class CarrierStringIO < StringIO
def original_filename
# the real name does not matter
"photo.jpeg"
end
def content_type
# this should reflect real content type, but for this example it's ok
"image/jpeg"
end
end
# some model with carrierwave uploader
class SomeModel
# the uploader
mount_uploader :photo, PhotoUploader
# this method will be called during standard assignment in your controller
# (like `update_attributes`)
def image_data=(data)
# decode data and create stream on them
io = CarrierStringIO.new(Base64.decode64(data))
# this will do the thing (photo is mounted carrierwave uploader)
self.photo = io
end
end
您可以使用Carrierwave-base64 Gem輕松實現這一點,您無需自己處理數據,只需添加gem並更改模型即可
mount_uploader :file, FileUploader
至
mount_base64_uploader :file, FileUploader
這就是它,現在你可以很容易地說:
Attachment.create(file: params[:file])
老問題但我不得不做類似的事情,從base64字符串上傳圖像,這是通過json請求傳遞的。 這就是我最終做的事情:
#some_controller.rb
def upload_image
set_resource
image = get_resource.decode_base64_image params[:image_string]
begin
if image && get_resource.update(avatar: image)
render json: get_resource
else
render json: {success: false, message: "Failed to upload image. Please try after some time."}
end
ensure
image.close
image.unlink
end
end
#some_model.rb
def decode_base64_image(encoded_file)
decoded_file = Base64.decode64(encoded_file)
file = Tempfile.new(['image','.jpg'])
file.binmode
file.write decoded_file
return file
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.