- xml - AJAX/Jquery XML 解析
- 具有多重继承的 XML 模式
- .net - 枚举序列化 Json 与 XML
- XML 简单类型、简单内容、复杂类型、复杂内容
我在使用 gem s3_direct_upload 时遇到困难。毫无疑问,我遵循了这些精彩的教程,但一无所获:
http://www.blitztheory.com/direct-upload-with-s3_direct_upload/
http://blog.littleblimp.com/post/53942611764/direct-uploads-to-s3-with-rails-paperclip-and
gem :“aws-sdk”、“s3_direct_upload”、“activeadmin”、“回形针”
Ruby:2.1.2,Rails:4.1.4
似乎脚本不工作,当我把一些文件放在那里时没有出现进度条,在日志中没有发送请求,即使我用 firefox 控制台查看也是如此。那么我应该怎么做才能使这项工作正常进行呢?
这是我的文件中的内容:
# config/schema.rb
ActiveRecord::Schema.define(version: 20140906145459) do
....
create_table "images", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
t.string "photo_file_name"
t.string "photo_content_type"
t.integer "photo_file_size"
t.datetime "photo_updated_at"
t.integer "gallery_id"
t.string "title"
t.string "photo_file_path"
t.string "direct_upload_url"
end
end
# app/models/image.rb
class Image < ActiveRecord::Base
belongs_to :gallery
acts_as_taggable
has_attached_file :photo,
:styles => { :small => '300x300>', :medium => '800x800>' },
:default_url => "images/:style/missing.png"
validates_attachment_content_type :photo, :content_type => /\Aimage\/.*\Z/
def self.copy_and_delete(paperclip_file_path, raw_source)
s3 = AWS::S3.new #create new s3 object
destination = s3.buckets[Rails.configuration.aws['bucket']].objects[paperclip_file_path]
sub_source = CGI.unescape(raw_source)
sub_source.slice!(0) # the attached_file_file_path ends up adding an extra "/" in the beginning. We've removed this.
source = s3.buckets[Rails.configuration.aws['bucket']].objects["#{sub_source}"]
source.copy_to(destination) #copy_to is a method originating from the aws-sdk gem.
source.delete #delete temp file.
end
end
# app/admin/image.rb
ActiveAdmin.register Image do
form partial: "form"
controller do
def create
if (params[:image][:attached_file_path])
@image = Image.new(image_params)
@gallery = Gallery.find(1)
@gallery.images << @image
respond_to do |format|
if @image.save!
paperclip_file_path = "images/photo/#{id_partition @image.id}/original/#{params[:image][:photo_file_name]}"
raw_source = params[:image][:photo_file_path]
Image.copy_and_delete paperclip_file_path, raw_source
format.html { redirect_to admin_image_path(@image), notice: 'Image was successfully created.' }
format.json { render :index, status: :created, location: @gallery }
else
format.html { render :new }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
else
@image = Image.new
render action: 'new', notice: "No file"
end
end
end
end
# app/views/admin/images/_form.html.erb
<%= s3_uploader_form callback_url: admin_images_url,
callback_param: "image[direct_upload_url]",
id: "s3-uploader" do %>
<%= file_field_tag :file, multiple: false %>
<% end %>
<div id="uploads_container"></div>
<script id="template-upload" type="text/x-tmpl">
<div id="file-{%=o.unique_id%}" class="upload">
{%= o.name %}
<div class="progress"><div class="bar" style="width: 0%"></div></div>
</div>
</script>
<br />
<%= semantic_form_for [:admin, @image] do |f| %>
<%if @image.errors.any? %>
<ul>
<% @image.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<%= f.inputs do %>
<%= f.input :title %>
<%= f.input :tag_list, hint: "Указывайте теги через запятую" %>
<%= f.hidden_field :direct_upload_url %>
<%= f.hidden_field :photo_file_name %>
<%= f.hidden_field :photo_file_size %>
<%= f.hidden_field :photo_content_type %>
<%= f.hidden_field :photo_file_path %>
<% end %>
<%= f.actions %>
<% end %>
# config/initializers/active_admin.rb
ActiveAdmin.setup do |config|
config.register_javascript 's3_direct_upload.js'
config.register_javascript 'direct_upload.js'
end
# app/assets/javascripts/direct_upload.js.coffee
jQuery ->
$("#s3_uploader").S3Uploader
remove_completed_progress_bar: false
remove_failed_progress_bar: true
progress_bar_target: $("#uploads_container")
allow_multiple_files: false
$("#s3_uploader").bind "s3_uploads_start", (e) ->
alert("Upload started")
$("#s3_uploader").bind "s3_upload_failed", (e, content) ->
alert content.filename + " failed to upload."
$("#s3_uploader").bind "s3_upload_complete", (e, content) ->
alert "Upload complete."
$("#image_direct_upload_url").val(content.url);
$("#image_photo_file_name").val(content.filename);
$("#image_photo_file_path").val(content.filepath);
$("#image_photo_file_size").val(content.filesize);
$("#image_photo_file_type").val(content.filetype);
$('#s3_uploader').bind "ajax:success", (e, data) ->
alert("server was notified of new file on S3; responded with '#{data}")
# config/initializers/aws.rb
require 'aws-sdk'
Rails.configuration.aws =
YAML.load(ERB.new(
File.read("#{Rails.root}/config/amazon_aws.yml")
).result)[Rails.env].symbolize_keys!
# config/initializers/paperclip.rb
Paperclip::Attachment.default_options.merge!(
url: ':s3_domain_url',
path: '/:class/:attachment/:id_partition/:style/:filename',
s3_permissions: {
original: :private
},
storage: :s3,
s3_credentials: Rails.configuration.aws #config/initializers/aws.rb
)
# config/initializers/s3_direct_upload.rb
S3DirectUpload.config do |c|
c.access_key_id = Rails.configuration.aws[:access_key_id]
c.secret_access_key = Rails.configuration.aws[:secret_access_key]
c.bucket = Rails.configuration.aws[:bucket]
c.region = nil
c.url = nil
end
# config/amazon_aws.yml
defaults: &defaults
access_key_id: "..."
secret_access_key: "..."
development:
<<: *defaults
bucket: "..."
test:
<<: *defaults
bucket: "..."
production:
access_key_id: <%= ENV["ACCESS_KEY_ID"]%>
secret_access_key: <%= ENV["SECRET_ACCESS_KEY"] %>
bucket: <%= ENV["S3_BUCKET_NAME"] %>
提前致谢。
更新
CORS 配置:
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>POST</AllowedMethod>
<AllowedMethod>PUT</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>*</AllowedHeader>
</CORSRule>
</CORSConfiguration>
更新 2
我曾尝试做各种事情,例如启用 javascript 或编写应始终显示的警报消息,但一切都没有结果。我做的最后一件事是使用回形针 + s3_direct_upload 创建简单的应用程序...出现了一个栏,应用程序正在尝试上传到 s3。现在我累了。肯定是app有问题。或 ActiveAdmin。明天试试。
最佳答案
是我的不慎,把一切都搞砸了。首先它在 js 文件中:
#= require active_admin/base
#= require s3_direct_upload
jQuery ->
$("#s3-uploader").S3Uploader
remove_completed_progress_bar: false
progress_bar_target: $("#uploads_container")
allow_multiple_files: false
$("#s3-uploader").bind "s3_upload_complete", (e, content) ->
alert "Upload complete."
$("#image_direct_upload_url").val content.url
$("#image_photo_file_name").val content.filename
$("#image_photo_file_path").val content.filepath
$("#image_photo_file_size").val content.filesize
我将与 s3Uploader 相关的代码放在 activeadmin.js.coffee 中,并将 ("#s3_uploader") 中的下划线替换为我表单中的连字符:
<%= s3_uploader_form callback_url: admin_images_url, callback_param: "direct_upload_url", id: "s3-uploader" do %>
<%= file_field_tag :file, multiple: false %>
<% end %>
另请注意,在 callback_url 中,我使用了 admin_images_url,因为它的 Controller 应处理此问题。
但这并不是每个地方都有效......在测试应用程序中一切都很好,但在我的主应用程序中却不行。问题出在 amazon_aws.yml 中。我删除了 access_key_id 和 secret_access_key 周围错误放置的引号,并且发送了 POST 请求。
仍然,由于 Controller 的原因,图像无法正确保存。使用 activeadmin 我这样做了:
ActiveAdmin.register Image do
permit_params :title, :tag_list, :direct_upload_url, :photo_file_name, :photo_file_size, :photo_content_type, :photo_file_path
form partial: "form"
controller do
def create
if params[:url]
@image = Image.new
render "new" and return
end
if (params[:image][:photo_file_path])
@image = Image.new(permitted_params[:image])
@gallery = Gallery.find(1)
@gallery.images << @image
respond_to do |format|
if @image.save!
paperclip_file_path = "images/photos/#{Paperclip::Interpolations.id_partition( @image.photo, "photo" )}/original/#{params[:image][:photo_file_name]}"
raw_source = params[:image][:photo_file_path]
Image.copy_delete_preprocess_save paperclip_file_path, raw_source, @image.id
format.html { redirect_to admin_image_path(@image), notice: 'Image was successfully created.' }
format.json { render :index, status: :created, location: @gallery }
else
format.html { render :new }
format.json { render json: @article.errors, status: :unprocessable_entity }
end
end
else
@image = Image.new
render action: 'new', notice: "No file"
end
end
end
end
然后我在图像模型中更改了方法 copy_delete_preprocess_save:
def self.copy_delete_preprocess_save(paperclip_file_path, raw_source, id)
s3 = AWS::S3.new #create new s3 object
destination = s3.buckets[Rails.configuration.aws[:bucket]].objects[paperclip_file_path]
sub_source = CGI.unescape(raw_source)
sub_source.slice!(0) # the attached_file_file_path ends up adding an extra "/" in the beginning. We've removed this.
source = s3.buckets[Rails.configuration.aws[:bucket]].objects["#{sub_source}"]
obj = source.copy_to(destination) #copy_to is a method originating from the aws-sdk gem and store returned object for preprocessing.
source.delete #delete temp file.
image = Image.find(id)
image.photo = obj.url_for(:get)
image.photo_file_path = nil
image.save!
end
我还应该提到 serious_c0der 建议的补丁。谢谢。
并且,作为典范,我在 active_admin.css.scss 中添加了这个字符串,使进度条可见:
@import "s3_direct_upload_progress_bars";
感谢您的帮助。希望它可以帮助某人。
关于ruby-on-rails - ruby on rails - s3_direct_upload 没有反应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25710603/
我是一名优秀的程序员,十分优秀!