Rails File Upload w/ Ajax Update?


#1

I’m trying to upload a file, display the upload progress and then
update a table with the newly uploaded file. Is there a way to
specify a :success handler for form_tag_with_upload_progress such that
I have access to the request.response data (in the way I can with
link_to_remote)?

The :finish JavaScript is being executed but because there is no
request object, the table doesn’t update. Any ideas on how to get
around this issue?

As a base, I’ve started with Typo’s Admin::ResourcesController and
modified it as such:

controller

def upload
begin
case request.method
when :post
file = params[:upload][:filename]
@up = Resource.create(:filename => file.original_filename,
:mime => file.content_type.chomp,
:user => session[:user],
:account => account,
:created_at => Time.now)

      @up.write_to_disk(file)

      @message = 'File uploaded: ' + file.size.to_s
      finish_upload_status "'#{@message}'"

      if request.xhr?
        @headers['resource-id'] = @up.id
        @headers['Content-Type'] = 'text/html; charset=utf-8'
        render :partial => 'resource', :layout => false, :locals

=> { :hidden => true }
end
end
rescue
@message = “‘Unable to upload #{file.original_filename}’”
@up.destroy unless @up.nil?
raise
end
end

view

<%= form_tag_with_upload_progress({:action => 'upload'}, { :begin => "new Effect.Appear('status')", :finish => "$('message').innertHTML = arguments[0]; new Effect.BlindUp('quick-resource', {duration: 0.4}); AjaxScaffold.updateResources(request, 'resource'); return false;" }) %> <%= file_field 'upload', 'filename' -%>
<%= submit_tag 'Upload' -%> or Cancel
<%= upload_status_tag %>
<%= end_form_tag %>
<%= @message %>
<tbody>
  <tr id="resource-empty-message" class="empty-message" <%= "

style=“display:none;” " if !@resources.empty? %>>



<tbody id="resource-list-body">
  <% if !@resources.empty? %>
    <%= render :partial => 'resource', :collection => @resources,

:locals => { :hidden => false } %>
<% else %>
<% # Do not remove the following TR, it is needed to load up
the even row color when enableHighlighting is turned on and the list
is empty %>




<% end %>
Filename (right-click for link) Uploaded By Uploaded At Content Type File Size Delete
No Entries

javascript (based on AjaxScaffold code)

updateResources: function(request, type) {
var resForm = request.responseText;
var id = this.getId(request,type);

new Insertion.Top(this.getTableBodyElement(type), resForm);

var resElement = this.getCreateElement(type, id);
Element.show(resElement);
TableBodyUtil.highlight(resElement,this.getTableBodyElement(type));

}

Many thanks in advance,
Sean


#2

I haven’t studied your code in detail, but let’s clarify one thing
first.
Without Kyles http://www.kylemaxwell.com/ iframe trick, the upload
itself
is not ajax (and will never be, because of security restrictions), just
the
uploadprogress is kind of ajax.