我使用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时,回形针/rails会失败。
Errno::ENOENT (No such file or directory - ????JFIF???我已经看到了创建临时文件的解决方案,但我很想知道是否有一种方法可以让Paperclip自动保存request.raw_post w/o,必须创建一个临时文件。有什么好主意或解决方案吗?
丑陋的解决方案(需要临时文件)
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吗?
发布于 2012-10-11 02:28:11
我以前的解决方案的问题是,临时文件已经关闭,因此不能再被Paper剪贴纸使用。下面的解决方案对我有效。这是最干净的方式,并(根据文档)确保您的诱惑文件被删除后使用。
将以下方法添加到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不要忘记在require 'tempfile'模型文件的顶部添加User。
https://stackoverflow.com/questions/12791764
复制相似问题