How to save a raw_data photo using paperclip

不打扰是莪最后的温柔 提交于 2019-11-30 20:45:10

The problem with my previous solution was that the temp file was already closed and therefore could not be used by Paperclip anymore. The solution below works for me. It's IMO the cleanest way and (as per documentation) ensures your tempfiles are deleted after use.

Add the following method to your User model:

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

Controller:

current_user.set_picture(request.raw_post)
current_user.save

Don't forget to add require 'tempfile' at the top of your User model file.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!