2

我正在按照本指南https://gist.github.com/stefanneculai/deed108fad534d0db3ff创建亚马逊签名。

  def getSignatureKey
    kDate    = OpenSSL::HMAC.digest('sha256', 'AWS4' + Figaro.env.aws_secret_access_key, Time.zone.now.utc.strftime('%Y%m%d'))
    kRegion  = OpenSSL::HMAC.digest('sha256', kDate, 'us-west-2')
    kService = OpenSSL::HMAC.digest('sha256', kRegion, 's3')
    kSigning = OpenSSL::HMAC.digest('sha256', kService, 'aws4_request')
    kSigning
  end

我正在将 froala gem 用于导轨并使用该imageUploadToS3选项。但是,在使用新的 Amazon 签名版本时出现此错误。

Encoding::UndefinedConversionError at /admin/campaigns/1/edit_content
"\xAC" from ASCII-8BIT to UTF-8

我试图将其更改为getSignatureKey.force_encoding("ISO-8859-1").encode("UTF-8"). 之后,服务器运行良好,当我上传图片时,我SignatureDoesNotMatch从亚马逊返回。

任何帮助将非常感激。

4

2 回答 2

1

Ivangrx 问我最终做了什么来解决这个问题。我最终没有采取这条路线将图像直接上传到 S3。相反,我在我的 froala 初始化中添加了一个 imageUploadURL。这是一个帖子请求,我担心我会做所有的工作。这就是我关心的样子。我正在使用 aws-sdk 的更新版本。

module Uploadable
  extend ActiveSupport::Concern
  # NOTE: This method must be set inside all controllers that are including this module
  # This is set this way so that it will throw an exception if you forget to create the method because that would
  # silently cause the image uploading to not work correctly.
  included do
    before_action :set_image_upload_path
  end

  def upload_image
    # Setup AWS credentials
    Aws.config.update(access_key_id: Figaro.env.aws_access_key_id,
                      secret_access_key: Figaro.env.aws_secret_access_key)

    s3 = Aws::S3::Resource.new(region: 'us-west-2')

    # Prepare the necessary parameters
    bucket = if Rails.env.production?
               'app-production'
             else
               'app-dev'
             end

    # If no user, then user_id_prefix will be nil which means the user id will just not be included in the filename
    name = build_unique_filename
    file = params[:file].tempfile

    # Create the image to upload
    image = s3.bucket(bucket).object(name)

    # Upload it and respond back to Froala but respond back to Airbrake with an error message
    if image.upload_file(file, acl: 'public-read')
      render json: { link: image.public_url }
    else
      Airbrake.notify_or_ignore(error_message: 'There was a problem uploading an image to the S3 account.')
    end
  end

  def build_unique_filename
    user_id_prefix = "#{(current_user || current_admin).id}-" if current_user || current_admin

    "#{controller_name}/#{user_id_prefix}#{Time.now.to_i}-" + params[:file].original_filename
  end
end

这非常有效,因为我能够为我的每个资源定义不同的上传路径,并在我的 S3 存储桶的特定目录中上传图像。如果您有任何问题,请发表评论。

于 2017-03-12T02:31:33.677 回答
1

只是一个猜测,但这个怎么样?

kDate    = OpenSSL::HMAC.digest('sha256', 'AWS4' + Figaro.env.aws_secret_access_key, Time.zone.now.utc.strftime('%Y%m%d')).encode("iso-8859-1").force_encoding("utf-8")

要不就

kDate    = OpenSSL::HMAC.digest('sha256', 'AWS4' + Figaro.env.aws_secret_access_key, Time.zone.now.utc.strftime('%Y%m%d')).encode("UTF-8")
于 2017-03-11T00:09:34.280 回答