使用 Backbone 上传文件 [英] File upload with Backbone
问题描述
我在 Rails 应用中使用 Backbone.js,我需要将文件上传作为其中一个 Backbone 模型的一部分.
I'm using Backbone.js in a Rails app and I need to do file uploads as part of one of the Backbone models.
我不相信 Backbone 允许开箱即用的多部分文件上传.有没有人设法通过一些插件或另一个外部库让它工作?我如何扩展 Backbone.js 以支持这一点?
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?
推荐答案
使用不同的方法经过几个月的试用后回答了我自己的问题.我的解决方案如下(使用 Rails).
Answering my own question after few months of trial using different methods. My solution is the following (with Rails).
对于任何需要文件上传的表单,我会设置 data-remote="true"
和 enctype="multipart/form-data"
并包含 rails.js 和 jquery.iframe-transport.js.
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.
使用 data-remote="true""noreferrer">rails.js 允许我绑定到 ajax:success
并在成功时创建 Backbone.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:
你显然应该绑定 ajax:error
来处理错误情况.
You should obviously bind ajax:error
to handle error cases.
对我来说,数据是在 ActiveRecord
模型中清理的,所以不必太担心 eval
语句.
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 控制器:
class PostsController < ApplicationController
respond_to :js
def create
@post = Post.create(params[:post])
respond_with @post
end
end
Rails 视图 (create.js.haml):
使用 remotipart gem.
这将处理表单上传文件时设置了 enctype
以及不上传的情况.
This will handle the case when the form does file uploads with enctype
being set, and when it doesn't.
您可以选择在此处对您的回复调用 sanitize
.
= remotipart_response do
- if remotipart_submitted?
= "eval(#{Yajl::Encoder.encode(@post)});"
- else
=raw "eval(#{Yajl::Encoder.encode(@post)});"
这篇关于使用 Backbone 上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!