Ruby 用葡萄和回形针上传文件
我正在开发一个REST API,试图上传一张用户的照片,使用:Ruby 用葡萄和回形针上传文件,ruby,ruby-on-rails-3,api,paperclip,Ruby,Ruby On Rails 3,Api,Paperclip,我正在开发一个REST API,试图上传一张用户的照片,使用: 微观框架 但它不工作,显示出这个错误 rails版本是3.2.8 找不到的处理程序# 我试着用一个控制器测试回形针,它成功了,但当我尝试通过GrapeAPI上传时,它不起作用,我的帖子标题是多部分/表单数据 我上传的代码是 user = User.find(20) user.picture = params[:picture] user.save! 因此,如果无法通过grape上载文件,有没有其他方法可以通过RE
- 微观框架
- 但它不工作,显示出这个错误
- rails版本是3.2.8
找不到的处理程序#
我试着用一个控制器测试回形针,它成功了,但当我尝试通过GrapeAPI上传时,它不起作用,我的帖子标题是多部分/表单数据
我上传的代码是
user = User.find(20)
user.picture = params[:picture]
user.save!
因此,如果无法通过grape上载文件,有没有其他方法可以通过REST api上载文件?您可以传递在
参数[:picture][:tempfile]
中获得的文件
对象,就像回形针为文件
对象提供适配器一样,如下所示
user.picture = params[:picture][:tempfile]
user.picture_file_name = params[:picture][:filename] # Preserve the original file name
@ahmad sherif解决方案可以工作,但您失去了原始的_文件名(和扩展名),这可能会给预处理器和验证器带来问题。您可以这样使用
ActionDispatch::Http::UploadedFile
:
desc“更新图像”
情妇
需要:id,:type=>String,:desc=>id
需要:image,:type=>Rack::Multipart::UploadedFile,:desc=>image文件
结束
帖子:图片怎么办
new_file=ActionDispatch::Http::UploadedFile.new(params[:image])
object=SomeObject.find(参数[:id])
object.image=新文件
object.save
结束
也许更一致的方法是为Hashie::Mash定义回形针适配器
module Paperclip
class HashieMashUploadedFileAdapter < AbstractAdapter
def initialize(target)
@tempfile, @content_type, @size = target.tempfile, target.type, target.tempfile.size
self.original_filename = target.filename
end
end
end
Paperclip.io_adapters.register Paperclip::HashieMashUploadedFileAdapter do |target|
target.is_a? Hashie::Mash
end
添加到wiki-为了Rails 5.1用户的利益,这也应该做到: /您的/endpoint/path 用户_spec.rb
这不管用:很容易,而且对carrierwave也很有魅力!如何在hashie mash中获得tempfile=#?我得到一个字符串,因此当尝试创建新的文件时,我得到了nil:NilClass的未定义的方法“unpack”#我们到底把它放在哪里?这取决于。对于grape on rails,您可以将此代码放入
config/initializers/paperclip\u hashie\u mash\u adapter.rb
。或者对grape on rake使用类似的smth:将其放到lib/paperclip\u hashie\u mash\u adapter.rb
中,并在加载应用程序依赖项之后但在应用程序启动之前需要它(例如config/application.rb
),谢谢,这很有帮助。我正在使用安装在轨道上的Grape,所以我刚刚创建了一个初始值设定项。
user = User.find(20)
user.picture = params[:picture]
user.save!
params do
required :avata, type: File
end
describe 'PATCH /users:id' do
subject { patch "/api/users/#{user.id}", params: params }
let(:user) { create(:user) }
let(:params) do
{
avatar: fixture_file_upload("spec/fixtures/files/jpg.jpg", 'image/jpeg')
}
end
it 'updates the user' do
subject
updated_user = user.reload
expect(updated_user.avatar.url).to eq(params[:avatar])
end
end