首页 > 解决方案 > Rails CarrierWave - 能够保存远程 url 图像但无法将本地图像文件保存到数据库和 AWS S3

问题描述

当我发出 POST 请求以发布“愿景”时,它会正确传递两个必需的参数。但是,保存后,HEROKU 数据库中的图像列为零,并且也不会在 AWS S3 中上传。

如何使用户可以将本地文件上传到 aws 和 heroku?

视力表:

class CreateVisions < ActiveRecord::Migration[5.1]
  def change
    create_table :visions do |t|
      t.string :image
      t.text :description

      t.timestamps
    end
  end
end

视觉.rb

class Vision < ApplicationRecord
    belongs_to :user
    mount_uploader :image, ImageUploader

end

visions_controller.rb 创建动作:

        def create
            @vision = current_user&.visions.build(vision_params)
            @vision.remote_image_url = 'https://www.gstatic.com/webp/gallery3/1.sm.png'

            @vision.save
            render :create, status: :created
        end

我正在像这样发出我的 POST 请求(它有效,但图像列仅在保存前在 visions_controller.rb 中传递远程 URL 时保存

let response = await fetch('https://prana-app.herokuapp.com/v1/visions/', {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
                'X-User-Email': this.state.email,
                'X-User-Token': this.state.accessToken
            },
            body: JSON.stringify({
              vision: {
                description: 'dsfsfdsfdsfsd',
                image: this.state.uploadFile
              }
            })
        });

setup_fog.rb

CarrierWave.configure do |config|
    config.fog_credentials = {
      provider: 'AWS',
      aws_access_key_id: ENV['AWS_ACCESS_KEY_ID'] || '',
      aws_secret_access_key: ENV['AWS_SECRET_ACCESS_KEY_ID'] || '',  
      region: 'us-west-2'
    }

    config.fog_directory = 'BUCKET_NAME'
    config.fog_public = false
    config.fog_attributes = {
      'Cache-Control' => "max-age=#{365.day.to_i}"
    }
  end

image_uploader.rb

  include CarrierWave::MiniMagick

  # Choose what kind of storage to use for this uploader:
  if Rails.env.production?
    storage :fog
  else
    storage :file
  end

  # Create different versions of your uploaded files:
  version :thumb do
    process resize_to_fit: [50, 50]
  end

  version :thumb do
  process resize_to_fit: [64, 64]
end

version :small do
  process resize_to_fit: [200,200]
end

version :large do
  process resize_to_fit: [1000,1000]
end

version :medium  do
  process resize_to_fit: [400,400]
end

  def extension_whitelist
     %w(jpg jpeg gif png)
  end

标签: ruby-on-railsrubyruby-on-rails-4amazon-s3carrierwave

解决方案


推荐阅读