首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >S3 + JQuery文件仅上载缓存文件到Shrine

S3 + JQuery文件仅上载缓存文件到Shrine
EN

Stack Overflow用户
提问于 2017-11-28 10:03:36
回答 1查看 459关注 0票数 0

这是rails的新手,我尝试过将Shrine和Jquery文件上传到S3,我得到了要上传的缓存文件,但图像从未上传过。我在上面关注了GoRails上的视频,但这些视频似乎非常过时。

我有一个Autos模型,它应该接受图像作为表单中的一个字段,用户模型通过devise,用户有许多auto_posts

Uploads.js:

代码语言:javascript
复制
    $(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

代码语言:javascript
复制
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

汽车控制器:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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

表格是

代码语言:javascript
复制
<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文件和汽车控制器的调整,但我在这里不知所措。感谢您的帮助

EN

回答 1

Stack Overflow用户

发布于 2018-02-15 04:46:37

你检查你的存储桶上的CORS设置了吗?Here's how the official docs recommend setting it.

从文档中:

代码语言:javascript
复制
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,
    }]
  }
)
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47522780

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档