使用Carrierwave将图像从客户端上传到Rails后端是最好的方法.现在我们的iOS开发人员正在以base64的形式发送文件,所以请求出现如下:
"image_data"=>"/9j/4AAQSkZJRgABAQAAAQABAAD/4QBYRXhpZgAATU0AKgAAAAgAAgESAAMAAAABAAEAAIdpAAQAAAABAAAAJgAAAAAAA6ABAAMAAAABAAEAAKACAAQAAAABAAAAHqADAAQAAAABAAAAHgAAAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAAeAB4DAREAAhEBAxEB/8QAHwAAAQUBAQE....
所以我的问题真的是两个问题.我应该告诉他以不同的文件格式发送吗?如果base64是正确的方式发送这些文件,那么我如何处理他们在载波?
解决方法
我认为一个解决方案可以将解码的数据保存到文件中,然后将该文件分配给挂载的上传器.之后,摆脱那个文件.
其他(内存中)解决方案可以是这样一个:
# 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