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?
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"andenctype="multipart/form-data"and include rails.js and jquery.iframe-transport.js.Setting
data-remote="true"with rails.js allows me to bind toajax:successand create the Backbone.js model on success.HTML:
JavaScript:
You should obviously bind
ajax:errorto handle error cases.For me, the data is sanitized in the
ActiveRecordmodel, so don’t have to worry too much about theevalstatement.Rails Controller:
Rails View (create.js.haml):
Using the remotipart gem.
This will handle the case when the form does file uploads with
enctypebeing set, and when it doesn’t.You could choose to call
sanitizeon your response here.