用葡萄和回形针上传文件 [英] uploading file with grape and paperclip

查看:46
本文介绍了用葡萄和回形针上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发 REST API,尝试上传用户照片:

I'm working on a REST API, trying to upload a picture of user with:

  • grape 微框架
  • paperclip gem 但它不起作用,显示此错误
  • rails 版本是 3.2.8
  • grape micro-framework
  • paperclip gem but it's not working, showing this error
  • rails version is 3.2.8

没有找到 #<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>类型=图像/png">

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

I tried testing paperclip with a controller and it worked but when I try to upload via grape api its not working my post header is multipart/form-data

我的上传代码是这样的

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

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

So if it is not possible to upload files via grape is there any alternative way to upload files via REST api?

推荐答案

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

@ahmad-sherif solution works but you loose original_filename (and extension) and that can provide probems with preprocessors and validators. You can use ActionDispatch::Http::UploadedFile like this:

  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

这篇关于用葡萄和回形针上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆