Backbone.js link file to model
I a开发者_Python百科m creating a web application using django and backbone.js. The problem is I need to upload files to the server. How do I link the backbone model with a file? Thus when I execute model.save() the file is uploaded to the server.
EDIT: just to make things clear. What I want to do is I want to link a input file box with the backbone model. So when the user selects a file from his/her computer I should be able to link that file with the backbone model. And when I call the model.save() in the backbone script it should send the file along with rest of the model.
Basically the Web browser decides when a file is uploaded, not the server. The server may receive the file in request.FILES. You can then handle the model.save() after the browser has submitted the file. For more information you should see Django's very good documentation site: http://docs.djangoproject.com/en/dev/topics/http/file-uploads/?from=olddocs
The model in backbone.js provides a means to use a model to process the data. BUt Django has its own facilities for receiving files as noted above.
The problem is that you can't use file upload with AJAX directly. The common workaround is to submit a form to a hidden iframe.
You can use jQuery Form plugin. It provides ajaxSubmit method, it works like jQuery.ajax call but uses hidden iframe so it can upload files.
Also you need to override Backbone.sync or override sync on a per-model basis and replace $.ajax call with $(someForm).ajaxSubmit call
On server you should return JSON string with id parameter and file parameter containing file url
精彩评论