11

我的客户正在尝试从黑莓和安卓手机上传图像。他们不喜欢发布 a) 表单参数或 b) 多部分消息。他们想要做的是只使用文件中的数据对 url 进行 POST。

这样的事情可以在 curl 中完成: 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
4

1 回答 1

18

这可以完成,但您仍然需要您的客户发送原始文件名(以及内容类型,如果您对类型进行任何验证)。

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.

于 2011-06-20T21:09:55.560 回答