我希望为我的Rails应用添加功能,以便将文件直接上传到Amazon S3。根据我的研究,一般的共识似乎是使用s3-swf-upload-plugin。我已经使用该gem设置了一个示例应用程序,但是我不能让它玩得很好而只允许选择单个文件。我还想创建一个上传记录,并使用回形针创建一个缩略图,我可以找到很少的指导。
所以我的问题是:
(1)我是否使用该宝石在正确的轨道上,或者我应该采取另一个appraoch?
(2)有哪些样品我可以用作参考?
非常感谢任何帮助。
克里斯
答案 0 :(得分:23)
尝试一个名为CarrierWaveDirect的新Gem,它允许您使用html表单将文件直接上传到S3,并轻松将图像处理移动到后台进程
答案 1 :(得分:6)
不确定是否可以轻松修改它,一次只上传一个文件,但这个宝石对我来说效果很好。它基于Ryan Bates' Railscast之一:
答案 2 :(得分:3)
尝试查看carrierwave https://github.com/jnicklas/carrierwave(支持s3) 使用carrierwave上传多文件并上传http://blog.assimov.net/post/4306595758/multi-file-upload-with-uploadify-and-carrierwave-on
答案 3 :(得分:1)
如果您使用的是Rails 3,请查看我的示例项目:
使用Rails 3,Flash和基于MooTools的FancyUploader直接上传到S3的示例项目:https://github.com/iwasrobbed/Rails3-S3-Uploader-FancyUploader
示例项目使用Rails 3,Flash / Silverlight / GoogleGears / BrowserPlus和基于jQuery的Plupload直接上传到S3:https://github.com/iwasrobbed/Rails3-S3-Uploader-Plupload
顺便说一句,您可以使用Paperclip进行后期处理,使用类似此博客文章描述的内容:
http://www.railstoolkit.com/posts/fancyupload-amazon-s3-uploader-with-paperclip
答案 4 :(得分:0)
我在Rails中使用Heroku's direct to S3 upload solution(使用jQuery-File-Upload和aws-sdk gem),因此可以使用ajax远程上传到S3。我希望这很有用:
<强> posts_controller.rb 强>
before_action :set_s3_direct_post, only: [:index, :create]
before_action :delete_picture_from_s3, only: [:destroy]
class PostsController < ApplicationController
def index
.
.
end
def create
@post = @user.posts.build(post_params)
if @post.save
format.html
format.js
end
end
def destroy
Post.find(params[:id]).destroy
end
private
def set_s3_direct_post
return S3_BUCKET.presigned_post(key: "uploads/#{SecureRandom.uuid}/${filename}", success_action_status: '201', acl: 'public-read')
end
def delete_picture_from_s3
key = params[:picture_url].split('amazonaws.com/')[1]
S3_BUCKET.object(key).delete
return true
rescue => e
# If anyone knows a good way to deal with a defunct file sitting in the bucket, please speak up.
return true
end
def post_params
params.require(:post).permit(:content, :picture_url)
end
end
<强> posts.html.erb 强>
<div class="info" data-url="<%= @s3_direct_post.url %>"
data-formdata="<%= (@s3_direct_post.fields.to_json) %>"
data-host="<%= URI.parse(@s3_direct_post.url).host %>">
</div>
表格
<%= form_for(:post, url: :posts, method: :post,
html: { class: "post_form", id: "post_form-#{post.id}" }
) do |f| %>
<%= f.text_area :content, id: "postfield-#{post.id}", class: "postText" %>
<%= f.button( :submit, name: "Post", title: "Post" ) do %>
<span class="glyphicon glyphicon-ok" aria-hidden="true"></span>
<% end %>
<span class="postuploadbutton" id="postUp-<%= post.id %>" title="Add file" >
<span class="glyphicon glyphicon-upload" aria-hidden="true"></span>
</span>
<span title="Cancel file" class="noticecancelupload" id="postCancel-<%= post.id %>" >
<span class="glyphicon glyphicon-remove-circle" aria-hidden="true"></span>
</span>
<%= f.file_field :picture_url, accept: 'image/jpeg,image/gif,image/png',
class: "notice_file_field", id: "postFile-#{post.id}" %>
<% end %>
<强> _post.html.erb 强>
<%= button_to post_path(
params: {
id: post.id,
picture_url: post.picture_url
}
),
class: 'btn btn-default btn-xs blurme',
data: { confirm: "Delete post: are you sure?" },
method: :delete do %>
<span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
<% end %>
每个_post.html.erb中的Javascript
$(document).off('click',"#postUp-<%= post.id %>");
$(document).on('click', '#postUp-<%= post.id %>', function(e) {
prepareUpload("#post_form-<%= post.id %>");
$('#postFile-<%= post.id %>').trigger("click");
});
$(document).off('click',"#postCancel-<%= post.id %>");
$(document).on('click', '#postCancel-<%= post.id %>', function(e) {
$(".appendedInput").remove(); // $('#postFile-<% post.id %>').val(""); doesn't work for me
$('.progBar').css('background','white').text("");
});
$(document).off('submit',"#post_form-<%= post.id %>"); // without this the form submitted multiple times in production
$(document).on('submit', '#post_form-<%= post.id %>', function(e) { // don't use $('#post_form-<%= post.id %>').submit(function() { so it doesn't bind to the #post_form (so it still works after ajax loading)
e.preventDefault(); // prevent normal form submission
if ( validatePostForm('<%= post.id %>') ) {
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
dataType: 'script'
});
$('#postCancel-<%= post.id %>').trigger("click");
}
});
function validatePostForm(postid) {
if ( jQuery.isBlank($('#postfield-' + postid).val()) && jQuery.isBlank($('#postFile-' + postid).val()) ) {
alert("Write something fascinating or add a picture.");
return false;
} else {
return true;
}
}
app.js中的Javascript
function prepareUpload(feckid) {
$(feckid).find("input:file").each(function(i, elem) {
var fileInput = $(elem);
var progressBar = $("<div class='progBar'></div>");
var barContainer = $("<div class='progress'></div>").append(progressBar);
fileInput.after(barContainer);
var maxFS = 10 * 1024 * 1024;
var info = $(".info");
var urlnumbnuts = info.attr("data-url");
var formdatanumbnuts = jQuery.parseJSON(info.attr("data-formdata"));
var hostnumbnuts = info.attr("data-host");
var form = $(fileInput.parents('form:first'));
fileInput.fileupload({
fileInput: fileInput,
maxFileSize: maxFS,
url: urlnumbnuts,
type: 'POST',
autoUpload: true,
formData: formdatanumbnuts,
paramName: 'file',
dataType: 'XML',
replaceFileInput: false,
add: function (e, data) {
$.each(data.files, function (index, file) {
if (file.size > maxFS) {
alert('Alas, the file exceeds the maximum file size of 10MB.');
form[0].reset();
return false;
} else {
data.submit();
return true;
}
});
},
progressall: function (e, data) {
var progress = parseInt(data.loaded / data.total * 100, 10);
progressBar.css('width', progress + '%')
},
start: function (e) {
progressBar.
css('background', 'orange').
css('display', 'block').
css('width', '0%').
text("Preparing...");
},
done: function(e, data) {
var key = $(data.jqXHR.responseXML).find("Key").text();
var url = '//' + hostnumbnuts + '/' + key;
var input = $('<input />', { type:'hidden', class:'appendedInput',
name: fileInput.attr('name'), value: url });
form.append(input);
progressBar.
css('background', 'green').
text("Ready");
},
fail: function(e, data) {
progressBar.
css("background", "red").
css("color", "black").
text("Failed");
}
});
});
} // function prepareUpload()
<强> create.js.erb 强>
$(".info").attr("data-formdata", '<%=raw @s3_direct_post.fields.to_json %>'); // don't use .data() to set attributes
$(".info").attr("data-url", "<%= @s3_direct_post.url %>");
$(".info").attr("data-host", "<%= URI.parse(@s3_direct_post.url).host %>");
$('.post_form')[0].reset();
$('.postText').val('');
<强>的application.js 强>
//= require jquery-fileupload/basic
<强>配置/初始化/ aws.rb 强>
Aws.config.update({
region: 'us-east-1',
credentials: Aws::Credentials.new(ENV['AWS_ACCESS_KEY_ID'], ENV['AWS_SECRET_ACCESS_KEY']),
})
S3_BUCKET = Aws::S3::Resource.new.bucket(ENV['S3_BUCKET'])
<强> 注意: 强>
此解决方案专为index.html.erb页面上的多个帖子表单而设计。这就是为什么@s3_direct_post
信息放在index.html.erb内的类info
的div中,而不是放在每个帖子中。这意味着,无论页面上的表单数量如何,页面上一次只显示一个@s3_direct_post
。只有在单击文件上传按钮时才会抓取@s3_direct_post
内的数据(通过调用prepareUpload()
)。提交后,在posts控制器中生成一个新的@s3_direct_post
,并且create {js.erb更新.info
内的信息。将@s3_direct_post
数据存储在表单中意味着可以同时存在许多不同的@s3_direct_post
实例,从而导致文件名生成错误。
您需要在帖子控制器索引操作(准备第一次上传)和创建操作(准备好第二次和后续上传)中:set_s3_direct_post
。
e.preventDefault();
阻止了正常表单提交,因此可以使用$.ajax({
“手动”完成。为什么不在表单中使用remote: true
?因为在Rails中,即使您尝试远程执行文件上传也是通过HTML请求和页面刷新完成的。
使用info.attr()
而不是info.data()
来设置和检索@s3_direct_post
属性,因为info.data没有更新
(例如,请参阅this问题)。这意味着您还必须使用jQuery.parseJSON()
手动将属性解析为对象(.data()实际上是自动执行的。)
请勿在application.js中使用//= require jquery-fileupload
。这个错误确实是一个真正的障碍(见here)。 original Heroku solution在我改变之前无效。
答案 5 :(得分:-1)
您可以使用Paperclip上传到S3(请参阅documentation)并创建缩略图,但先将文件上传到临时文件夹,然后才能在将文件上传到S3之前应用图像处理。
至于这种配置的例子,整个博客圈和StackOverflow上有很多这样的配置,例如: this