Question

I've got the uploader working from the Railscast #383, but is there a way to add and remove the uploader link via ajax?

I would also need to pass in the "service" instance id.

The code I would like to add or remove via ajax is below:

<%= s3_uploader_form post: images_url(:service_id => service.id), as: "image[url]" do %>
  <%= file_field_tag :file, multiple: true %>
 <% end %>

 <script id="template-upload" type="text/x-tmpl">
   <div class="upload">
     {%=o.name%}
     <div class="progress"><div class="bar" style="width: 0%"></div></div>
   </div>
  </script>
Was it helpful?

Solution

Ok I figured it out. The main problem I was having is that the uploader coffeescript was not executing again after the form was added via ajax. The revised #136 railscast got the basic ajax form working, but in order to get the uploader form working via ajax, I just included uploader coffeescript as normal javascript in my new.js.erb file. That way when the new.js.erb file is executed, it loads the form and executes the uploader javascript.

new.js.erb:

$('#new_link').hide().after('<%= j render("images/form") %>');

jQuery(function() {
  return $('#fileupload').fileupload({
    add: function(e, data) {
      var file, types;
      types = /(\.|\/)(gif|jpe?g|png)$/i;
      file = data.files[0];
      if (types.test(file.type) || types.test(file.name)) {
        data.context = $(tmpl("template-upload", file));
        $('#fileupload').append(data.context);
        data.form.find('#content-type').val(file.type);
        return data.submit();
      } else {
        return alert("" + file.name + " is not a gif, jpeg, or png image file");
      }
    },
    progress: function(e, data) {
      var progress;
      if (data.context) {
        progress = parseInt(data.loaded / data.total * 100, 10);
        return data.context.find('.bar').css('width', progress + '%');
      }
    },
    done: function(e, data) {
      var content, domain, file, path, to;
      file = data.files[0];
      domain = $('#fileupload').attr('action');
      path = $('#fileupload input[name=key]').val().replace('${filename}', file.name);
      to = $('#fileupload').data('post');
      content = {};
      content[$('#fileupload').data('as')] = domain + path;
      $.post(to, content);
      if (data.context) {
        return data.context.remove();
      }
    },
    fail: function(e, data) {
      alert("" + data.files[0].name + " failed to upload.");
      console.log("Upload failed:");
      return console.log(data);
    }
  });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top