使用Carrierwave将原始文件上传到Rails [英] Uploading a raw file to Rails using Carrierwave
问题描述
我的客户正在尝试从Blackberry和Android手机上传图片。他们不喜欢发布a)表单参数或b)多部分消息。他们想做的是仅用文件中的数据对URL进行POST。
My clients are trying to upload an image from Blackberry and Android phones. They don't like posting a)form parameters or b) multipart messages. What they would like to do is do a POST to a url with only the data from the file.
类似的事情可以在curl中完成:
curl -d @ google.png http://server/postcards/1/photo.json -X POST
Something like this can be done in curl:
curl -d @google.png http://server/postcards/1/photo.json -X POST
我希望将上传的照片放入明信片模型的照片属性中,并放入正确的目录中。
I'd like the uploaded photo to put into the photo attribute of the postcards model and into the right directory.
我正在控制器中执行类似操作,但是图像在目录中已损坏。我现在正在将文件手动重命名为 png:
I'm doing something like this in the controller but the image is corrupted in the directory. I am doing a manual renaming of the file to a "png" for now:
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
推荐答案
可以这样做,但是您仍然需要客户端发送原始文件名(如果对类型进行任何验证,则还要发送内容类型)。
This can be done but you will still need your clients to send the orignal filename (and the content-type if you do any validation on the type).
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
。
这篇关于使用Carrierwave将原始文件上传到Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!