什么是从客户端上传图片到使用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宝石 ,你不必自己处理数据,你要做的就是添加了宝石和改变从模型
mount_uploader :file, FileUploader
至
mount_base64_uploader :file, FileUploader
和多数民众赞成它,现在你可以轻松地说:
Attachment.create(file: params[:file])
老问题,但我不得不做类似的事情,从中通过JSON请求传递的base64字符串上传图片。 这是我落得这样做:
#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