简体   繁体   中英

Shrine + JQuery File Upload only uploading cache file to S3

Fairly new to rails and trying out Shrine and Jquery File Uploads to S3, I got the cache file to upload but the image never gets uploaded. I was following the GoRails videos on it but it seems like those are horribly outdated.

I have an Autos model which is supposed to accept images as one of the fields in the form, a Users model through devise and a user has many 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

Autos controller:

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

My Routes.rb:

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

The form is

<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>

I'm sure it's just an easy tweak to the uploads.js file and the autos controller but I'm at a loss here as to what to do. I appreciate any help

Did you check the CORS settings on your bucket? Here's how the official docs recommend setting it.

From the docs:

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,
    }]
  }
)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM