使用Carrierwave将原始文件上载到Rails

jev*_*evy 11 ruby-on-rails-3 carrierwave

我的客户正在尝试从Blackberry和Android手机上传图片.他们不喜欢发布a)表单参数或b)多部分消息.他们想要做的是只用文件中的数据对URL进行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
Run Code Online (Sandbox Code Playgroud)

该模型:

class Postcard < ActiveRecord::Base
  mount_uploader :photo, PhotoUploader
end
Run Code Online (Sandbox Code Playgroud)

Sam*_*uel 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
Run Code Online (Sandbox Code Playgroud)

现在您可以使用设置照片了

curl http://server/postcards/1/photo.json?filename=foo.png --data-binary @foo.png
Run Code Online (Sandbox Code Playgroud)

并指定内容类型使用&type=image/png.