我的客户正在尝试从Blackberry和Android手机上传图片。他们不喜欢发布a)表单参数或b)多部分消息。他们想做的是只对文件中的数据进行网址POST。
这样的事情可以在卷曲中完成:
curl -d @google.png http://server/postcards/1/photo.json -X POST
我希望将上传的照片放入明信片模型的照片属性并放入正确的目录。
我在控制器中做了类似的事情,但目录中的图像已损坏。我现在正在手动将文件重命名为“png”:
def PostcardsController < ApplicationController
...
# Other RESTful methods
...
def photo
@postcard = Postcard.find(params[:id])
@postcard.photo = request.body
@postcard.save
end
模特:
class Postcard < ActiveRecord::Base
mount_uploader :photo, PhotoUploader
end
答案 0 :(得分:18)
这可以完成,但您仍然需要您的客户发送orignal文件名(如果您对该类型进行任何验证,则需要内容类型)。
def photo
tempfile = Tempfile.new("photoupload")
tempfile.binmode
tempfile << request.body.read
tempfile.rewind
photo_params = params.slice(:filename, :type, :head).merge(:tempfile => tempfile)
photo = ActionDispatch::Http::UploadedFile.new(photo_params)
@postcard = Postcard.find(params[:id])
@postcard.photo = photo
respond_to do |format|
if @postcard.save
format.json { head :ok }
else
format.json { render :json => @postcard.errors, :status => :unprocessable_entity }
end
end
end
现在您可以使用
设置照片了curl http://server/postcards/1/photo.json?filename=foo.png --data-binary @foo.png
并指定内容类型使用&type=image/png
。