我正在开发一个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">
我尝试使用控制器测试回形针,但是当我尝试通过葡萄api上传它不起作用我的帖子标题是multipart / form-data
我上传的代码是
user = User.find(20)
user.picture = params[:picture]
user.save!
因此,如果无法通过葡萄上传文件,还有其他方法可以通过REST api上传文件吗?
答案 0 :(得分:16)
@ 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
答案 1 :(得分: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
并使用它&#34;透明&#34;
user = User.find(20)
user.picture = params[:picture]
user.save!
已添加到维基 - https://github.com/intridea/grape/wiki/Uploaded-file-and-paperclip
答案 2 :(得分:2)
您可以传递File
中的params[:picture][:tempfile]
对象,因为Paperclip获得了File
个对象的适配器,就像这样
user.picture = params[:picture][:tempfile]
user.picture_file_name = params[:picture][:filename] # Preserve the original file name
答案 3 :(得分:0)
对于Rails 5.1用户来说,这也应该做:
params do
required :avata, type: File
end
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