文件上传与骨干网 [英] File upload with Backbone

查看:107
本文介绍了文件上传与骨干网的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails应用程序中使用Backbone.js的,我需要做的文件上传为骨干的车型之一的一部分。

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

我不相信骨干允许多部分文件上传开箱。有没有人设法得到它通过一些插件或其他外部的lib工作吗?如何延长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).

有关的任​​何形式的需要文件上传我会成立数据远程=真正的 ENCTYPE =的multipart / form-data的,包括 rails.js 和<一个href=\"https://github.com/cmlenz/jquery-iframe-transport/blob/master/jquery.iframe-transport.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.

设置数据远程=真正的 rails.js 让我绑定到 AJAX:成功并创建成功的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:误差处理错误的情况下

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

对我来说,数据消毒在的ActiveRecord 模式,所以不必担心评估<太多/ code>语句。

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 宝石。

当表单做文件上传与是enctype 是一套,而这将处理情况下,当它没有。

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)});"

这篇关于文件上传与骨干网的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆