用葡萄和回形针上传文件

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

  • 葡萄微框架
  • 回形针gem,但它不起作用,显示此错误
  • 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=# type="image/png">

我尝试使用控制器测试回形针,但是当我尝试通过葡萄api上传它不起作用我的post标题是multipart / form-data

我的上传代码就是这个

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

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

@ ahmad-sherif解决方案可以工作,但是你放弃了original_filename(和扩展名),并且可以为probems提供预处理器和validation器。 您可以像这样使用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 

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

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

 user.picture = params[:picture][:tempfile] user.picture_file_name = params[:picture][:filename] # Preserve the original file name