2017-11-28 4 views
0

かなり新しいレールを試して試してみてください。ShrineとJquery File S3にアップロードすると、アップロードするキャッシュファイルがありますが、イメージはアップロードされません。私はそれにGoRailsのビデオに従っていたが、それらはひどく時代遅れであるように思える。Shrine + JQuery File S3にキャッシュファイルをアップロードするだけです

は、私は、フォーム内のフィールドの一つ、工夫を通じてユーザーモデルなどの画像を受け入れることになっている自動車のモデルを持っており、ユーザーは多くの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 

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

フォームが、私はそれがuploads.jsファイルや自動車のコントローラにだけ簡単に微調整だと確信してい

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

ですが、私はによここで何をすべきかについての損失。私は助けていただきありがとうございます

+0

GoRailsのスクリーンキャストが "恐ろしく時代遅れ" であってはならない、変更さ唯一の事は、 'presign_endpoint'プラグインが' direct_upload'を置き換えることです。 'config/routes.rb'とフォームを投稿できますか? 「画像がアップロードされない」とはどういう意味ですか?私が理解したように、イメージはクライアント側のS3にアップロードされますが、レコードに添付されていませんか?イメージのJSONデータがRailsアプリケーションに送信されますか? –

+0

フォームとroutes.rbファイルのコードを追加しました。イメージを選択すると、S3バケットにキャッシュファイルが表示されますが、イメージはS3バケットに表示されません。 [これは画像を選択する際のレールのログです](https://i.imgur.com/EmKNaW1.png) –

+0

Railsのログが正しく見えるので、ファイルデータが正しくアプリケーションに送信されたように見えます。他に何が間違っているのか分かりません。 'Shrine.plugin:logging'を使ってShrineログを有効にすると、キャッシュされたファイルが永続的なストレージにアップロードされるのを確認できますか?また、 '@ auto.save'の前と後に' @ auto.image'の内容は何ですか? –

答えて

0

バケツのCORS設定を確認しましたか?ドキュメントから Here's how the official docs recommend setting it.

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, 
    }] 
    } 
) 
関連する問題