这是rails的新手,我尝试过将Shrine和Jquery文件上传到S3,我得到了要上传的缓存文件,但图像从未上传过。我在上面关注了GoRails上的视频,但这些视频似乎非常过时。
我有一个Autos模型,它应该接受图像作为表单中的一个字段,用户模型通过devise,用户有许多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表格是
<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文件和汽车控制器的调整,但我在这里不知所措。感谢您的帮助
发布于 2018-02-15 04:46:37
你检查你的存储桶上的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,
}]
}
)https://stackoverflow.com/questions/47522780
复制相似问题