用葡萄和回形针上传文件

use*_*061 7 ruby api paperclip ruby-on-rails-3

我正在开发一个REST API,尝试上传用户的图片:

  • 葡萄微框架
  • 回形针宝石,但它不起作用,显示此错误
  • rails版本是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! 
Run Code Online (Sandbox Code Playgroud)

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

lis*_*i.r 17

@ ahmad-sherif解决方案可以工作,但是你放弃了original_filename(和扩展名),并且可以为probems提供预处理器和验证器.你可以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
Run Code Online (Sandbox Code Playgroud)


Dmi*_*dov 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
Run Code Online (Sandbox Code Playgroud)

并"透明地"使用它

 user = User.find(20) 
 user.picture = params[:picture] 
 user.save! 
Run Code Online (Sandbox Code Playgroud)

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


Ahm*_*rif 2

您可以传递File您获得的对象,params[:picture][:tempfile]因为 Paperclip 有一个对象适配器File,如下所示

user.picture = params[:picture][:tempfile]
user.picture_file_name = params[:picture][:filename] # Preserve the original file name
Run Code Online (Sandbox Code Playgroud)