如何使用回形针保存 raw_data 照片 [英] How to save a raw_data photo using paperclip

查看:57
本文介绍了如何使用回形针保存 raw_data 照片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 jpegcam 允许用户拍摄网络摄像头照片以设置为他们的个人资料照片.该库最终将原始数据发布到我在 Rails 控制器中获得的服务器,如下所示:

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 controller like so:

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 时,这不起作用并且回形针/导轨失败.

This does not work and paperclip/rails fails when you try to save request.raw_post.

Errno::ENOENT (No such file or directory - ????JFIF???

我见过制作临时文件的解决方案,但我很想知道是否有办法让 Paperclip 自动保存 request.raw_post 而不必制作临时文件.有什么优雅的想法或解决方案吗?

I've seen solutions that make a temporary file but I'd be curious to know if there is a way to get Paperclip to automatically save the request.raw_post w/o having to make a tempfile. Any elegant ideas or solutions out there?

丑陋的解决方案(需要临时文件)

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吗?

This is ugly as it requires a temporary file to be saved on the server. Tips on how to make this happen w/o the temporary file needing to be saved? Can StringIO be used?

推荐答案

我之前的解决方案的问题是临时文件已经关闭,因此无法再被 Paperclip 使用.下面的解决方案对我有用.这是 IMO 最干净的方式,并且(根据文档)确保您的临时文件在使用后被删除.

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.

将以下方法添加到您的 User 模型:

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

控制器:

current_user.set_picture(request.raw_post)
current_user.save

不要忘记在 User 模型文件的顶部添加 require 'tempfile'.

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

这篇关于如何使用回形针保存 raw_data 照片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆