我正在用Rails 5开发一个api应用程序,从客户端我有一个Anuglar应用程序。
我有以下要求:
我读过关于CarrierWave和回形针的文章,但是我没有发现我怎么做所有这些要求。
我非常感谢任何涉及所有这些需求的建议、库、创业板等等。
发布于 2016-07-18 19:18:28
我用CarrierWave gem实现了类似的东西。假设您希望将图像附加到模型Post。
在模型中:
class Post < ActiveRecord::Base
has_many :photos, inverse_of: :post
end然后,您可以拥有一个照片模型:
class Photo < ActiveRecord::Base
belongs_to :post
mount_uploader :post_image, PostImageUploader
end然后您可以将其添加到app/uploaders/post_image_uploader.rb中。
class PostImageUploader < CarrierWave::Uploader::Base
# Create different versions of your uploaded files:
version :standard do
process resize_to_fit: [800, 800]
end
version :thumb do
process resize_to_fit: [100, 100]
end
end因为您是通过api创建映像的,所以您必须将图像转换为Base64字符串并以param的形式发送。在本例中,在将base64字符串发送到服务器之前,它位于param [:photo][:photo_data]中。在photos_controller.rb中有以下内容:
def create
@photo = Photo.new(photo_params)
@photo.post_image = decode_photo_data(params[:photo][:photo_data])
if @photo.save
render json: @photo, status: :created, location: @photo
else
render json: @photo.errors, status: :unprocessable_entity
end
end
#decode base64 data to an jpg image:
def decode_photo_data(photo_data)
data = StringIO.new(Base64.decode64(photo_data))
data.class.class_eval { attr_accessor :original_filename, :content_type }
data.original_filename = "upload.jpg"
data.content_type = "image/jpg"
# return decoded data
data
end
def photo_params
params.require(:photo).permit(:caption, :post_id)
end这样,当您向您的端点发出post请求时,其主体如下
{"photo": {"caption": "an image", "post_id": 1, "photo_data":<your image base64 string>}} 它将为带有photo of 1的post创建一个具有standard和thumb版本的post。
https://stackoverflow.com/questions/38443570
复制相似问题