jquery fileupload rails s3 shrine image upload error

时间:2017-11-08 02:04:15

标签: ruby-on-rails c9.io jquery-fileupload-rails shrine

我对rails很新,我正在尝试使用Shrine将图像直接上传到S3。我直接上传到S3以完美地工作,但是,当我介绍jquery文件上传并上传图像时,Chrome控制台抛出 this error 对我。我不确定我做错了什么,我似乎无法在网上找到任何解决方案。我知道这是一个预设错误,它可能没有找到缓存链接,但我不知道如何解决它。

编辑:这是通过在路由文件中包含预设代码并将uploads.js中的存储位置更改为正确的位置来解决的。但是,现在,我在尝试上载时回滚的文件存在问题。

我正在使用基于云的ide C9,

这是我的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);
        });
  }
  }); 
});

我的routes.rb文件包括:

mount ImageUploader::UploadEndpoint => "/images/upload"

mount Shrine.presign_endpoint(:cache) => "/autos/upload/cache/presign"

我有一个模型接受这些图像以及其他名为Autos的字段,这包含在Autos文件中:

include ImageUploader[:image]

我的汽车控制器是:

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[:auto])

    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[:auto])
      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

2 个答案:

答案 0 :(得分:1)

假设您的image_uploader.rb已定义ImageUploader类并且假设您的预设端点类似于/autos/upload/cache/presign,则您的routes.rb应该具有如此定义的预设路线:< / p>

mount ImageUploader.presign_endpoint(:cache) => '/autos/upload/cache/presign'

我希望路径文件中的这个单一更改会使您能够获得应包含3个键的预设对象:urlfieldsheaders

# GET /autos/upload/cache/presign
{
  "url": "https://my-bucket.s3-eu-west-1.amazonaws.com",
  "fields": {
    "key": "cache/b7d575850ba61b44c8a9ff889dfdb14d88cdc25f8dd121004c8",
    "policy": "eyJleHBpcmF0aW9uIjoiMjAxNS0QwMToxMToyOVoiLCJjb25kaXRpb25zIjpbeyJidWNrZXQiOiJzaHJpbmUtdGVzdGluZyJ9LHsia2V5IjoiYjdkNTc1ODUwYmE2MWI0NGU3Y2M4YTliZmY4OGU5ZGZkYjE2NTQ0ZDk4OGNkYzI1ZjhkZDEyMTAwNGM4In0seyJ4LWFtei1jcmVkZW50aWFsIjoiQUtJQUlKRjU1VE1aWlk0NVVUNlEvMjAxNTEwMjQvZXUtd2VzdC0xL3MzL2F3czRfcmVxdWVzdCJ9LHsieC1hbXotYWxnb3JpdGhtIjoiQVdTNC1ITUFDLVNIQTI1NiJ9LHsieC1hbXotZGF0ZSI6IjIwMTUxMDI0VDAwMTEyOVoifV19",
    "x-amz-credential": "AKIAIJF55TMZYT6Q/20151024/eu-west-1/s3/aws4_request",
    "x-amz-algorithm": "AWS4-HMAC-SHA256",
    "x-amz-date": "20151024T001129Z",
    "x-amz-signature": "c1eb634f83f96b69bd675f535b3ff15ae184b102fcba51e4db5f4959b4ae26f4"
  },
  "headers": {}
}

上传开始后,您现在可以在开发者控制台中找到此对象,而不是之前的404 not found错误。

更新

我认为你非常接近解决方案。在create/update操作中,使用auto_params[:auto]代替auto_params

您还想查看Association Basics for collection methods

上的RoR指南

答案 1 :(得分:0)

我认为您遵循gorails直接上传s3的教程 在您的gem文件中,确保使用正确的Roda版本 gem'roda',“〜> 2.29.0”