神社 jQuery文件仅上传将缓存文件上传到S3



相当新的铁轨,尝试将神社和jQuery文件上传到S3,我得到了高速缓存文件上传,但图像永远不会上传。我正在关注Gorails的视频,但似乎这些视频已经过时了。

我有一个汽车模型,该模型应该接受图像作为表单中的字段之一,通过deaise和用户的用户模型具有许多auto_posts

uploads.js:

    $(document).on("turbolinks:load", function(){
   $("[type=file]").fileupload({
      add: function(e, data) {
          console.log("add", data);
          data.progressBar = $('<div class="progress"><div class="determinate" style="width: 70%"></div></div>').insertBefore("form")
          var options = {
              extension: data.files[0].name.match(/(.w+)?$/)[0], //set the file extention
             _: Date.now() //prevent caching
          };
          $.getJSON("/autos/upload/cache/presign", options, function(result) {
              console.log("presign", result);
              data.formData = result['fields'];
              data.url = result['url'];
              data.paramName = "file";
              data.submit()
          });
      },
      progress: function(e, data) {
      console.log("progress", data);
      var progress = parseInt(data.loaded / data.total * 100, 10);
      var percentage = progress.toString() + '%'
      data.progressBar.find(".progress-bar").css("width", percentage).html(percentage);
      },
      done: function(e, data) {
      console.log("done", data);
      data.progressBar.remove();

      var image = {
        id: data.formData.key.match(/cache/(.+)/)[1], // we have to remove the prefix part
        storage:  'cache',
        metadata: {
          size: data.files[0].size,
          filename: data.files[0].name.match(/[^/\]+$/)[0], // IE return full path
          mime_type: data.files[0].type
        }
      }
      form = $(this).closest("form");
      form_data = new FormData(form[0]);
      form_data.append($(this).attr("name"), JSON.stringify(image))
      $.ajax(form.attr("action"), {
        contentType: false,
        processData: false,
        data: form_data,
        method: form.attr("method"),
        dataType: "json"
        }).done(function(data) {
            console.log("done from rails", data);
            });
      }
   }); 
});

Shrine.rb

require "shrine/storage/s3"
s3_options = {
  access_key_id:     Rails.application.secrets.aws_access_key_id,
  secret_access_key: Rails.application.secrets.aws_secret_access_key,
  region:            Rails.application.secrets.aws_region,
  bucket:            Rails.application.secrets.aws_bucket,
}
Shrine.storages = {
  cache: Shrine::Storage::S3.new(prefix: "cache",upload_options: {acl: "public-read"}, **s3_options),
  store: Shrine::Storage::S3.new(prefix: "store",upload_options: {acl: "public-read"}, **s3_options),
}
Shrine.plugin :presign_endpoint
Shrine.plugin :activerecord
Shrine.plugin :direct_upload
Shrine.plugin :restore_cached_data

汽车控制器:

class AutosController < ApplicationController
     before_action :find_auto, only: [:show, :edit, :update, :destroy]
   def index
       @autos = Auto.all.order("created_at DESC")
   end
   def show
   end
    def new
        @auto = current_user.autos.build
    end
    def create
      @auto = current_user.autos.build(auto_params)
      if @auto.save
          flash[:notice] = "Successfully created post."
          redirect_to autos_path
      else
          render 'new'
      end
    end
    def edit
       end
    def update
         if @auto.update(auto_params)
             flash[:notice] = "Successfully updated post."
            redirect_to auto_path(@auto)
        else
            render 'edit'
    end
    end
    def destroy
    @auto.destroy
    redirect_to autos_path
    end
    private 
   def auto_params
    params.require(:auto).permit(:title, :price, :description, :contact, :image, :remove_image)
end
def find_auto
    @auto = Auto.find(params[:id])     
end
end

我的路由:

Rails.application.routes.draw do
  #mount ImageUploader::UploadEndpoint => "/images/upload"
  mount Shrine.presign_endpoint(:cache) => "/autos/upload/cache/presign"
    devise_for :users
    resources :autos
    resources :jobs
    root 'index#index'
    get 'categories', to: 'index#categories'
    get 'about', to: 'pages#about'
    get 'getstarted', to: 'pages#getstarted'
end

表格是

<div class="container">
    <div class="card-panel">
        <% if @auto.errors.any? %>
        <% @auto.errors.full_messages.each do |msg| %>
        <script type="text/javascript">
    Materialize.toast('<%= msg %>', 10000, 'red')
  </script>
  <% end %>
  <% end %>   
<%= simple_form_for @auto do |f| %>
  <%= f.file_field :image %>
<%= f.input :title, label: "Name of Vehicle" %>
<%= f.input :price, label: "Asking Price" %>
<%= f.input :description %>
<%= f.input :contact, label: "Contact Info" %>
<%= f.button :submit, class: "btn light-blue darken-3" %>
<%= link_to "Cancel", autos_path, class: "btn waves-effect waves-light red 
accent-4" %>
<% end %>
</div>
</div>

我敢肯定,这只是对uploads.js文件和汽车控制器的简单调整,但是我在这里做什么。感谢任何帮助

您是否检查了存储桶上的CORS设置?这是官方文档建议设置它的方式。

来自文档:

require "aws-sdk-s3"
client = Aws::S3::Client.new(
  access_key_id:     "<YOUR KEY>",
  secret_access_key: "<YOUR SECRET>",
  region:            "<REGION>",
)
client.put_bucket_cors(
  bucket: "<YOUR BUCKET>",
  cors_configuration: {
    cors_rules: [{
      allowed_headers: ["Authorization", "Content-Type", "Origin"],
      allowed_methods: ["GET", "POST"],
      allowed_origins: ["*"],
      max_age_seconds: 3000,
    }]
  }
)

最新更新