How to save a raw_data photo using paperclip

前端 未结 1 962
有刺的猬
有刺的猬 2021-01-05 15:29

I\'m using jpegcam to allow a user to take a webcam photo to set as their profile photo. This library ends up posting the raw data to the sever which I get in my rails contr

相关标签:
1条回答
  • 2021-01-05 16:22

    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.

    0 讨论(0)
提交回复
热议问题