我正在开发 REST API,尝试上传用户图片:
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">
我尝试用 Controller 测试回形针并且它有效但是当我尝试通过 grape api 上传时它不起作用我的帖子标题是 multipart/form-data
我的上传代码是这样的
user = User.find(20)
user.picture = params[:picture]
user.save!
如果不能通过 grape 上传文件,有没有其他方法可以通过 REST api 上传文件?
最佳答案
@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
关于ruby - 用葡萄和回形针上传文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14067163/