使用Paperclip gem保存从Facebook获取的个人资料图像

use*_*569 2 ruby facebook ruby-on-rails paperclip ruby-on-rails-3

我试图找出如何让用户从他们的计算机上传照片或从Facebook获取照片.

我已经有一个表单用于上传图像并使用Paperclip插件保存它.这很好.

我已经设置了Facebook身份验证,并使用Koala gem访问Facebook图形API.

我已经写过这个方法:

def fetch_fb_picture
 unless current_user.authentications.blank?  
  @graph = Koala::Facebook::GraphAPI.new(current_user.authentications.find_by_provider("facebook").token)
  @picture = @graph.get_picture("#{current_user.authentications.find_by_provider('facebook').username}")
  current_user.profile.photo = @picture
 end
end
Run Code Online (Sandbox Code Playgroud)

我相信Koala gem返回图像的url.但是,由于我正在使用paperclip gem,我的配置文件接受以下属性:

t.string   "photo_file_name"
t.string   "photo_content_type"
t.integer  "photo_file_size"
Run Code Online (Sandbox Code Playgroud)

因此,如何将Facebook图像正确保存到数据库中?

Dom*_*nic 6

你可以这样做:

r = open("http://graph.facebook.com/#{@user.facebook_id}/picture")
image_data = r.read
file_size = r.length
mime_type = "image/jpeg" #fb photos always are jpg
#write data to database, or save as temp file and upload to S3
Run Code Online (Sandbox Code Playgroud)

我不建议这样做,因为Faceboook图将始终返回用户的图像,因为它们总是公开可用.您只需要在他们的ID或用户名之后调用/图片.你可以有一个布尔值来查看它是否是facebook用户,只需使用ID来显示图像.这也将确保您拥有最新的Facebook照片.

if @user.facebook_image?
   image_tag "http://graph.facebook.com/#{@user.facebook_id}/picture"
else
   image_tag @user.photo.url(:thumb)
end
Run Code Online (Sandbox Code Playgroud)