简体   繁体   English

使用Rails,Backbone,Remotipart上传AJAX图像

[英]AJAX image upload with Rails, Backbone, Remotipart

I've been using Remotipart successfully to upload images via AJAX for a while now, but we've recently decided to go the Backbone route, and now since my forms are rendered via JS templates, I'm no longer able to use the :remote => true syntax to generate the Iframe transport code. 我已经使用Remotipart成功通过AJAX上传图像已有一段时间了,但是我们最近决定采用Backbone路线,现在由于我的表单是通过JS模板呈现的,因此我不再能够使用: remote => true语法,用于生成iframe传输代码。 I don't want to have to figure out how to do this manually. 我不想弄清楚如何手动执行此操作。 Any thoughts on how I can get Remotipart to work when using JS templates? 关于使用JS模板时如何使Remotipart工作的任何想法?

Figured out a solution. 找出解决方案。 I was a little confused on how the JS for Remotipart works. 我对Remotipart的JS的工作方式有些困惑。 After a little research, here's what I found: 经过一些研究,这是我发现的内容:

Remotipart works simply by binding to the ajax:aborted:file event, which is triggered when jQuery UJS (which handles traditional AJAX form submits) detects a file within the form. Remotipart的工作原理是绑定到ajax:aborted:file事件,该事件在jQuery UJS(处理传统AJAX表单提交)检测到表单中的文件时触发。 Since that script (along with the dependent iFrame transport plugin) is already included on the page, all you need to do is manually add 由于该脚本(以及相关的iFrame传输插件)已包含在页面上,因此您所需要做的就是手动添加

data-remote="true"

to your form. 到您的表格。 jQuery has an .on() event bound to forms with such attributes, so if you include that, Remotipart will be triggered. jQuery具有绑定到具有此类属性的表单的.on()事件,因此,如果包括该事件,则将触发Remotipart。

Another issue, though, is that if this form is submitted, it will still likely fail to upload the file due to the lack of the CSRF token. 但是,另一个问题是,如果提交此表单,由于缺少CSRF令牌,它仍可能无法上传文件。 The solution is to manually add a hidden input tag with the token. 解决方案是使用令牌手动添加隐藏的输入标签。

Here's the final markup that worked for me (I'm using .eco templates with a little jQuery to grab the value of the CSRF meta tags on the page): 这是对我有用的最终标记(我将.eco模板与一个jQuery结合使用,以获取页面上CSRF meta标签的值):

<form accept-charset="UTF-8" id="image-upload-form" action="/projects/<%= @project.get('id') %>" method="post" enctype="multipart/form-data" data-remote="true">
    <input name="project[cover_photo]" type="file" />
    <input type="hidden" name="<%= $('meta[name="csrf-param"]').attr('content') %>" value="<%= $('meta[name="csrf-token"]').attr('content') %>" />
    <input name="_method" type="hidden" value="put" />
    <button id="add-photo">Save</button>
</form>

Hope this will help spare someone else the same trouble I had! 希望这可以帮助其他人摆脱与我同样的麻烦!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM