带有REST API的示例Rails4应用程序,该应用程序使用回形针上传到Amazon S3 [英] Sample rails4 application with REST API which uses paperclip to upload to Amazon S3

查看:75
本文介绍了带有REST API的示例Rails4应用程序,该应用程序使用回形针上传到Amazon S3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以分享给我一个示例应用程序,该应用程序具有REST API可以将图像上传到Amazon S3.我已经在Google上搜索了很多,但大多数都没有按预期工作.

Can someone share me a sample application , that has REST APIs to upload images to Amazon S3 . I've googled a lot , but most of them are not working as expected .

我们将不胜感激.

推荐答案

要通过API上传图像,您可以在前端将图像转换为 base64 格式并将其发送到服务器.在服务器中,您可以将base64数据转换为图像,然后通过paperclip将其保存到S3.

For uploading images through API you can convert the images to base64 format in front end and send it to server. In, server you can convert the base64 data into the image and save it to S3 via paperclip.

class User < ActiveRecord::Base
    before_save :decode_picture_data, :if => :picture_data_provided?
    has_attached_file :avatar,
                    :storage => :s3, :s3_protocol => 'https',
                    :bucket => # S3_Bucket,
                    :url => '/user/:id/:basename_:id.:extension',
                    :s3_credentials => {
                        :access_key_id => # Access key id,
                        :secret_access_key => # Secret access key
                    },
                    :path => '/user/:id/:basename_:id.:extension',
                    :default_url => ""

  validates_attachment_content_type :avatar, :content_type => %w(image/jpeg image/jpg image/png)

  private

  def picture_data_provided?
    !self.picture_data.blank?
  end

  def decode_picture_data
    # If cover_image_data is set, decode it and hand it over to Paperclip
    data = StringIO.new(Base64.decode64(self.picture_data))
    data.class.class_eval { attr_accessor :original_filename, :content_type }
    data.original_filename = SecureRandom.hex(16) + ".png"
    data.content_type = "image/png"
    self.avatar = data
    self.picture_data = nil
  end
end

在这里,picture_dataUser表中的一列,其中包含通过API params从客户端接收的 base64 数据.

Here, picture_data is a column in User table which has the base64 data received from the client through API params.

您可以在上面的代码中指定自己的S3 URL和路径.

You can specify your own S3 URL and path in above code.

在上面的代码中,来自客户端的picture_data被解码并通过Paperclip保存在S3中.

In the above code the picture_data that came from the client side is decoded and saved in S3 via Paperclip.

这篇关于带有REST API的示例Rails4应用程序,该应用程序使用回形针上传到Amazon S3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆