Sunday, May 19, 2024
51
rated 0 times [  56] [ 5]  / answers: 1 / hits: 17378  / 13 Years ago, tue, june 28, 2011, 12:00:00

I'm using Backbone.js in a Rails app and I need to do file uploads as part of one of the Backbone models.



I don't believe Backbone allows for multi-part file upload out of the box. Has anyone managed to get it working via some plugin or with another external lib? How can I extend Backbone.js to support this?


More From » ruby-on-rails

 Answers
26

Answering my own question after few months of trial using different methods. My solution is the following (with Rails).



For any form that requires file upload I would set data-remote=true and enctype=multipart/form-data and include rails.js and jquery.iframe-transport.js.



Setting data-remote=true with rails.js allows me to bind to ajax:success and create the Backbone.js model on success.



HTML:



<form action=/posts.js method=post data-remote=true enctype=multipart/form-data>
<input type=text name=post[message] />
<input type=file name=post[file] />
<button>Submit</button>
</form>


JavaScript:



You should obviously bind ajax:error to handle error cases.



For me, the data is sanitized in the ActiveRecord model, so don't have to worry too much about the eval statement.



$('form').bind('ajax:success', function(event, data) {
new Model(eval(data)); // Your newly created Backbone.js model
});


Rails Controller:



class PostsController < ApplicationController
respond_to :js

def create
@post = Post.create(params[:post])
respond_with @post
end
end


Rails View (create.js.haml):



Using the remotipart gem.



This will handle the case when the form does file uploads with enctype being set, and when it doesn't.



You could choose to call sanitize on your response here.



= remotipart_response do
- if remotipart_submitted?
= eval(#{Yajl::Encoder.encode(@post)});
- else
=raw eval(#{Yajl::Encoder.encode(@post)});

[#91474] Saturday, June 25, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
domeniccolti

Total Points: 276
Total Questions: 98
Total Answers: 93

Location: India
Member since Fri, May 13, 2022
2 Years ago
domeniccolti questions
Mon, Oct 18, 21, 00:00, 3 Years ago
Thu, Oct 14, 21, 00:00, 3 Years ago
Thu, Jul 15, 21, 00:00, 3 Years ago
Sat, Oct 24, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;