如何使用回形针保存raw_data照片
我正在使用jpegcam允许用户将网络摄像头照片设置为他们的个人资料照片。 这个库最终将原始数据发布到我在rails控制器中获得的服务器,如下所示:
def ajax_photo_upload # Rails.logger.info request.raw_post @user = User.find(current_user.id) @user.picture = File.new(request.raw_post)
当您尝试保存request.raw_post时,这不起作用并且paperclip / rails失败。
Errno::ENOENT (No such file or directory - ????JFIF???
我已经看到了制作临时文件的解决方案,但我很想知道是否有办法让Paperclip自动保存request.raw_post,而不必制作临时文件。 有优雅的想法或解决方案吗?
UGLY SOLUTION(需要临时文件)
class ApiV1::UsersController < ApiV1::APIController def create File.open(upload_path, 'w:ASCII-8BIT') do |f| f.write request.raw_post end current_user.photo = File.open(upload_path) end private def upload_path # is used in upload and create file_name = 'temp.jpg' File.join(::Rails.root.to_s, 'public', 'temp', file_name) end end
这很难看,因为它需要在服务器上保存一个临时文件。 有关如何实现这一点的提示没有需要保存的临时文件? 可以使用StringIO吗?
我以前的解决方案的问题是临时文件已经关闭,因此Paperclip不再使用它。 以下解决方案适合我。 IMO是最干净的方式,并且(根据文档)确保您的临时文件在使用后被删除。
将以下方法添加到您的User
模型:
def set_picture(data) temp_file = Tempfile.new(['temp', '.jpg'], :encoding => 'ascii-8bit') begin temp_file.write(data) self.picture = temp_file # assumes has_attached_file :picture ensure temp_file.close temp_file.unlink end end
控制器:
current_user.set_picture(request.raw_post) current_user.save
不要忘记在User
模型文件的顶部添加require 'tempfile'
。