Multiple files upload with Rails 3 and paperclip on heroku - ruby-on-rails

I need an interface on my Rails 3 app to upload multiple files to Amazon S3 (because i'm on heroku), possibly with progress bars.
I've easily managed how to set up paperclip and upload single files, but i'm really lost now on how to go ahead.
Please can you give me some advices? It's 2 days i'm searching across all the internet, but i can't find a working solution
** EDIT **
I really can't understand... I'm going mad 'cause I'm losing too many hours on this... please help me.
If I try to open the example app cited by Johnny I only get this (and in my app it is the same):
Where is the UI?
Is there something wrong on my browser?
** EDIT 2 **
Here on GitHub you can find my testapp... please can you explain me why the damn upload UI is not showing up? Thanks!
** EDIT 3 **
Thank you very much Johnny, i wasn't aware of the fact that jquery and prototype can't live together.
Now the plugin is showing up correctly, but as a try to upload something it creates a new "upload" record, but its attachment field is blank, and the files are not on s3.
This is what the console is saying:
Started POST "/uploads" for 127.0.0.1 at 2011-06-27 16:17:22 +0200
Processing by UploadsController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"GesRBTiZR1f2LV/bAeAdxWqF++gxcDJw4pPGStYGsH8=", "upload"=>{"attachment"=>[#<ActionDispatch::Http::UploadedFile:0x000001032834b8 #original_filename="animal-tiger-66550.jpg", #content_type="image/jpeg", #headers="Content-Disposition: form-data; name=\"upload[attachment][]\"; filename=\"animal-tiger-66550.jpg\"\r\nContent-Type: image/jpeg\r\n", #tempfile=#<File:/var/folders/Qj/QjEqvUUNGTmuki5SXOaaG++++TI/-Tmp-/RackMultipart20110627-1818-1syiex9>>]}}
AREL (0.5ms) INSERT INTO "uploads" ("attachment", "created_at", "updated_at", "attachment_file_name", "attachment_content_type", "attachment_file_size", "attachment_updated_at") VALUES (NULL, '2011-06-27 14:17:23.049136', '2011-06-27 14:17:23.049136', NULL, NULL, NULL, NULL)
[paperclip] Saving attachments.
Completed 200 OK in 64ms (Views: 4.2ms | ActiveRecord: 0.7ms)

You can look at jQuery-File-Upload. Demo here and rails 3/Paperclip setup here.
Edit: As #apneadiving mentioned, the library has been updated to version 5. The script you have is for verison 4. You should try modifying this to work with PaperClip. Copy-pasting the majority of the example code into my app (with a few modifications) worked for me:
#app/public/javascripts/application.js
$(function () {
// Initialize the jQuery File Upload widget:
$('#fileupload').fileupload();
// Load existing files:
$.getJSON($('#fileupload form').prop('action'), function (files) {
var fu = $('#fileupload').data('fileupload');
fu._adjustMaxNumberOfFiles(-files.length);
fu._renderDownload(files)
.appendTo($('#fileupload .files'))
.fadeIn(function () {
// Fix for IE7 and lower:
$(this).show();
});
});
// Open download dialogs via iframes,
// to prevent aborting current uploads:
$('#fileupload .files a:not([target^=_blank])').live('click', function (e) {
e.preventDefault();
$('<iframe style="display:none;"></iframe>')
.prop('src', this.href)
.appendTo('body');
});
});
#app/controllers/uploads_controller.rb
def create
#upload = Upload.new(params[:upload])
if #upload.save
render :json => [{
:pic_path => #upload.attachment.url.to_s ,
:name => #upload.attachment.instance.attributes["picture_file_name"]
}], :content_type => 'text/html'
else
render [:json => { :result => 'error'}], :content_type => 'text/html'
end
end
#app/views/uploads/new.html.haml
%link#theme{:href => "http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.13/themes/base/jquery-ui.css", :rel => "stylesheet"}
= stylesheet_link_tag 'jquery.fileupload-ui'
#fileupload
= form_for Upload.new, :html => { :multipart => true } do |f|
.fileupload-buttonbar
%label.fileinput-button
%span Add files...
= f.file_field :attachment, :multiple => true
%button.start{:type => "submit"} Start upload
%button.cancel{:type => "reset"} Cancel upload
%button.delete{:type => "button"} Delete files
.fileupload-content
%table.files
.fileupload-progressbar
%script#template-upload{:type => "text/x-jquery-tmpl"}
%tr{:class => "template-upload{{if error}} ui-state-error{{/if}}"}
%td.preview
%td.name ${name}
%td.size ${sizef}
{{if error}}
%td.error{:colspan => "2"}
Error:
{{if error === 'custom_failure'}}Custom Error Message
{{else}}${error}
{{/if}}
{{else}}
%td.progress
%div
%td.start
%button Start
{{/if}}
%td.cancel
%button Cancel
%script#template-download{:type => "text/x-jquery-tmpl"}
%tr{:class => "template-download{{if error}} ui-state-error{{/if}}"}
{{if error}}
%td
%td.name ${name}
%td.size ${sizef}
%td.error{:colspan => "2"}
Error:
{{if error === 1}}File exceeds upload_max_filesize (php.ini directive)
{{else}}${error}
{{/if}}
{{else}}
%td.preview
{{if thumbnail_url}}
%a{:href => "${url}", :target => "_blank"}
%img{:src => "${thumbnail_url}"}/
{{/if}}
%td.name
<a href="${url}"{{if thumbnail_url}} target="_blank"{{/if}}>${name}
%td.size ${sizef}
%td{:colspan => "2"}
{{/if}}
%td.delete
%button{"data-type" => "${delete_type}", "data-url" => "${delete_url}"} Delete
Edit
Had a quick look at your app, the problem is that you are mixing prototype with jquery. The easiest way around this is to switch to jQuery using jquery-rails.
#Gemfile
gem 'jquery-rails'
Next, run bundle install and then rails g jquery:install.
Then change your app/views/layouts/application.erb to this:
<%= stylesheet_link_tag :all %>
<%= csrf_meta_tag %>
<%= javascript_include_tag 'jquery.min' %>
<%= javascript_include_tag 'jquery-ui-1.8.13.custom.min' %>
<%= javascript_include_tag 'jquery.tmpl.min' %>
<%= javascript_include_tag 'jquery.iframe-transport' %>
<%= javascript_include_tag 'jquery.fileupload' %>
<%= javascript_include_tag 'jquery.fileupload-ui' %>
<%= javascript_include_tag 'jquery_ujs' %>
<%= javascript_include_tag 'application' %>
Note that I removed the
<%= javascript_include_tag :defaults %>
So that I can specify the order in which jquery, jquery_ujs, and application are loaded.

I've begun with a very similar task recently, and the swf plugin (at least the more recent one) will indeed let you update paperclip's record. It has callbacks for just about everything you'd need to extend.
:onUploadComplete (upload_options,event)
Here's Nathan Colgate's gist on the matter. He just makes a remote call to the rails server once the upload is finished telling it of the locations for the paperclip attachment.
from his uploadCompleteHandler
var uploadCompleteHandler = function(upload_options,event){
$.ajax({
url: '<%= notify_rails_of_successful_upload_path(:format => :js)%>',
global: false,
type: 'POST',
data: ({
'authenticity_token' : '<%= form_authenticity_token %>',
'upload' : {
'file_file_name' : upload_options.FileName,
'file_file_size' : upload_options.FileSize,
'file_content_type' : upload_options.ContentType
}
}),
dataType: 'script'
}
)
};
I'm not sure if this exact callback gets triggered for each file; it definitely looks like it would. But he passes everything paperclip needs back through an ajax request. filename,size,content-type. This way all that gets sent to heroku is some text about the file, sparing your app a good amount of work by giving it to the client.
edit: flash is the only way I've found to avoid sending a lot of data through heroku to s3. There are a few html5/js-only uploaders that might be able to get the job done, but the ones I have found are still pretty ripe on the dev tree.

As per Heroku support, see this.
Paperclip & multiple files upload, although not S3 specific.

View: (notice the array blog_post[avatars][])
<form accept-charset="UTF-8" action="/blog_posts" enctype="multipart/form-data" id="new_blog_post" method="post">
<div style="margin:0;padding:0;display:inline">
<input name="utf8" type="hidden" value="✓" />
<input name="authenticity_token" type="hidden" value="<%=form_authenticity_token %>" />
</div>
<p><input id="blog_post" name="blog_post[avatars][]" type="file" multiple /></p>
<p><input name="commit" type="submit" value="Upload" /></p>
</form>
Controller:
# POST /blog_posts
# POST /blog_posts.json
def create
#blog_post = BlogPost.new(params[:blog_post])
#blog_post.avatars.each do |avatar|
each_blog_post = BlogPost.new
each_blog_post.avatar = avatar
if each_blog_post.save
end
end
end
Model:
class BlogPost < ActiveRecord::Base
attr_accessible :title, :avatar, :avatars
has_attached_file :avatar
attr_accessor :avatars
end

Related

I can't upload files > 1MB using dropzonejs, ruby-on-rails and puma

I am trying to make a web application where people can upload their files, which will be stored on the hard drive then. I am using dropzonejs to handle the file uploads and ruby-on-rails to create my web application.
The problem is that whenever I try to upload a file that is bigger than 1 MB it just hangs on 99.9999% and never gets uploaded fully.
My form is:
<%= form_tag '/upload', html: {multipart: true}, class: "dropzone" , id: "media-dropzone" do %>
<div class="fallback">
<%= file_field_tag "files", multiple: true%>
</div>
<% end %>
The associated javascript is:
<script src="/assets/dropzone.js" type="text/javascript">
var TOKEN=$('meta[name="csrf-token"]').attr('content');
Dropzone.autoDiscover = false;
var dz = new Dropzone("div#mydropzone",{
url: "/upload_file/upload",
autoProcessQueue:false,
uploadMultiple:true,
addRemoveLinks:true,
maxFiles:2,
parallelUploads:2,
acceptedFiles: text/xml,
params:{
'authenticity_token': TOKEN
} });
$('form').submit(function(e) {
if(dz.getQueuedFiles().length > 0) {
e.preventDefault();
dz.processQueue();
}
});
</script>
My rails server runs puma 3.9.1
EDIT
A picture of the hanging upload
Thanks to #Pavel, I remembered to install nginx, and this fixed my problem

Rails 4.2 upgrade: Asset names passed to helpers should not include the "/assets/" prefix

I upgraded from Rails 4.1 to 4.2. I get the following error now:
Sprockets::Rails::Helper::AbsoluteAssetPathError at /
Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/spinner.gif", use "spinner.gif"
The error message is clear. However, I don't know what it's talking about. It highlights this line of code:
<div class="loading">
<%= image_tag asset_path('spinner.gif') %>
</div>
I do not use the literal string '/assets/' in that line of code. So what is this error referring to?
I was able to resolve that specific error by removing the call to asset_path and just using image_tag 'spinner.gif'; however, I still get the error right here (I am using Paperclip gem):
<%= image_tag current_user.avatar.url(:thumb) %>
caused by this:
ActionController::Base.helpers.asset_path('missing-user.png')
Again, it is complaining about asset_path.
UPDATE:
Error only occurs when I pass asset_path to image_tag method:
ActionController::Base.helpers.asset_path('missing-user.png')
=> "/assets/missing-user.png"
helper.image_tag(ActionController::Base.helpers.asset_path('missing-user.png'))
Sprockets::Rails::Helper::AbsoluteAssetPathError: Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/missing-user.png", use "missing-user.png"
image_tag will pass the source option to asset_path on its own:
image_tag("icon")
# => <img alt="Icon" src="/assets/icon" />
image_tag("icon.png")
# => <img alt="Icon" src="/assets/icon.png" />
image_tag("/icons/icon.gif", height: '32', width: '32')
# => <img alt="Icon" height="32" src="/icons/icon.gif" width="32" />
So when you call image_tag asset_path('spinner.gif') you're actually doing image_tag( '/assets/spinner.gif' ) which is why you get the sprockets warning.
I resolved the issue but I still don't understand the WHY factor. This only happens when I upgraded from Rails 4.1 to 4.2. Check this out:
ActionController::Base.helpers.asset_path('missing-user.png')
=> "/assets/missing-user.png"
helper.image_tag "/assets/missing-user.png"
Sprockets::Rails::Helper::AbsoluteAssetPathError: Asset names passed to helpers should not include the "/assets/" prefix. Instead of "/assets/missing-user.png", use "missing-user.png"
helper.image_tag "missing-user.png"
=> "<img src=\"/assets/missing-user.png\" alt=\"Missing user\" />"
Based on the above, image_tag does not want you to pass it the literal path string 'assets'. Consequently, in my Paperclip gem helper, I had to od this:
has_attached_file :avatar,
styles: { normal: "128x128>", thumb: "40x40>" },
default_style: :thumb,
default_url: ->(attachment) { 'missing-user.png' }
In other words, I had to remove this:
ActionController::Base.helpers.image_url('missing-user.png')
since image_url returns the string '/assets/missing-user.png'.

Simple_form_for not using AJAX?

I got a weird problem with my form:
= simple_form_for([#item, #item_comment], :remote => true, id: "new_item_comment", :url => item_item_comments_path(#item)) do |f|
= f.input :comment, :label => false
= f.submit "Save", :class => "btn_save left"
Which in my opinion should call:
Started POST "/de-de/items/20150423/item_comments" for 127.0.0.1 at 2015-04-23 12:29:33 +0200
Processing by ItemCommentsController#create as JSON
but instead I get it as HTML:
Started POST "/de-de/items/20150423/item_comments" for 127.0.0.1 at 2015-04-23 12:29:33 +0200
Processing by ItemCommentsController#create as HTML
It used to work but without changing these parts, it only uses HTML.
Does anyone have an idea on how to solve this?
--- Update 1 ---
I added these lines to my coffeescript:
$('form[data-remote]').submit (e)->
e.preventDefault()
$.rails.handleRemote $('form[data-remote]')
And it works but I'm not really satisfied with this solution since I don't know what caused the problem.
Usually it happened to me in 2 cases:
I had a file input on the form (which forces ruby to skip remote: true option)
I had troubles with jquery-ujs javascript file (which actually processes rails html attrs)
So please check your generated html if it has <form .... data-remote='true'..> and check that jquery-ujs (or whatever handler you want to use) is included in a page javascripts.
If you are still having troubles after this, you can put a breakpoint somewhere in jquery-ujs

rails form action missing route

Ruby 1.9.3 and using HAML.
Trying to build a form to go to a specific action, but having problem with routing. The code on the form is
%form#feedback_form{:action=>"give_feedback_account_path", :method => 'post', :style => "padding: 0 5px;"}
%input{:name => "authenticity_token", :value => form_authenticity_token, :type => "hidden"}
blah blah blah
.field
%input#feedback_submit{:type => "submit", :value => "give feedback"}
When I try to submit the form I get a 404 response, and looking at the server log gives me...
Started POST "/give_feedback_account_path" for 127.0.0.1 at 2014-06-03 10:07:12 +0100
ActionController::RoutingError (No route matches "/give_feedback_account_path"):
When I run rake routes to get the details I get
give_feedback_account POST /account/give_feedback(.:format)
{:action=>"give_feedback", :controller=>"accounts"}
What am I missing?
Your url is /give_feedback_account_path, which is not good. To fix it, you can use form_tag helper:
= form_tag give_feedback_account_path, method: 'post', style: 'padding: 0 5px;' do
// your form goes here
change this
:action=>"give_feedback_account_path"
to this
:action => give_feedback_account_path
give_feedback_account_path is a method. You want to call it, to get the actual path.

Rails: using the calendar_date_select gem

Environment: Rails 3.2.3, ruby 1.9.3-p125
My gemfile has the following in it:
gem 'calendar_date_select'
my layouts/application.html.erb has the following statement (as the last statement in the head section):
<%= calendar_date_select_includes %>
I installed the gem via gem install calendar_date_select
and ran rake bundle:install
I read the documentation, and some of the responses on StackOverflow, and here's what I ended up putting in my view:
<%= form_for(#panel) do |f| %>
.......
Start Date/Time: <%= f.calendar_date_select :start_time, :iso_date => true %>
I am getting the following error message:
undefined method `calendar_date_select' for #<#:0x007fae3b136938>
Any ideas?
I've switched from using that gem to just using jqueryUI which has the same functionality.
To do that:
view
= f.text_field :content_date, id: 'datepicker', size:10
= f.time_select :content_date, :ignore_date => true # Added later. not shown in screenshot
Gemfile
# Nothing - jquery & jqueryUI are now the default.
# Check web pages to see what really gets included (in the header).
application.js
%script
# The main code
$(function() {
$( "#datepicker" ).datepicker();
});
# This makes the pop-up show the actual db date by fixing a format difference.
$(function (){
var dateInput = $("#datepicker");
var format = 'yy-mm-dd';
dateInput.datepicker({dateFormat: format});
dateInput.datepicker('setDate', $.datepicker.parseDate(format, dateInput.val()));
});
Use this code to enable time in calender select tag
<%= f.calendar_date_select "date", :time => true , :readonly=>true, :popup=>"force" %>

Resources