7

我正在研究一个 REST API,试图上传一张用户的图片

  • 葡萄微框架
  • 回形针宝石,但它不起作用,显示此错误
  • 轨道版本是 3.2.8

No handler found for #<Hashie::Mash filename="user.png" head="Content-Disposition: form-data; name=\"picture\"; filename=\"user.png\"\r\nContent-Type: image/png\r\n" name="picture" tempfile=#<File:/var/folders/7g/b_rgx2c909vf8dpk2v00r7r80000gn/T/RackMultipart20121228-52105-43ered> type="image/png">

我尝试使用控制器测试回形针并且它有效但是当我尝试通过葡萄 api 上传时它不起作用我的帖子标题是 multipart/form-data

我的上传代码是这个

 user = User.find(20) 
 user.picture = params[:picture] 
 user.save! 

因此,如果无法通过葡萄上传文件,有没有其他方法可以通过 REST api 上传文件?

4

4 回答 4

17

@ahmad-sherif 解决方案有效,但您丢失了 original_filename (和扩展名),并且可以为探针提供预处理器和验证器。你可以ActionDispatch::Http::UploadedFile这样使用:

  desc "Update image"
  params do
    requires :id, :type => String, :desc => "ID."
    requires :image, :type => Rack::Multipart::UploadedFile, :desc => "Image file."
  end
  post :image do
    new_file = ActionDispatch::Http::UploadedFile.new(params[:image])
    object = SomeObject.find(params[:id])
    object.image = new_file
    object.save
  end
于 2013-06-24T12:46:20.197 回答
8

也许更一致的方法是为 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

并“透明地”使用它

 user = User.find(20) 
 user.picture = params[:picture] 
 user.save! 

添加到维基 - https://github.com/intridea/grape/wiki/Uploaded-file-and-paperclip

于 2013-11-16T01:35:05.047 回答
2

你可以传递File你得到的对象,params[:picture][:tempfile]因为 Paperclip 有一个File对象适配器,像这样

user.picture = params[:picture][:tempfile]
user.picture_file_name = params[:picture][:filename] # Preserve the original file name
于 2012-12-28T12:49:29.787 回答
0

为了 Rails 5.1 用户,这也应该这样做:

/你的/端点/路径

params do
  required :avata, type: File
end

users_spec.rb

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
于 2018-12-31T16:12:57.853 回答