Rails 4:如何使用 AJAX 上传文件 [英] Rails 4: How to upload files with AJAX

查看:69
本文介绍了Rails 4:如何使用 AJAX 上传文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用 AJAX 上传文件.过去,我通过使用神奇的 jQuery 表单插件 实现了这一点,并且效果很好.目前我正在构建一个 Rails 应用程序并尝试做一些Rails 方式"的事情,所以我使用 Form Helper 和 paperclip gem 添加文件附件.

I want to upload files with AJAX. In the past I accomplished this by using the magical jQuery form plugin and it worked great. Currently I'm building a Rails app and trying to do things "The Rails Way" so I'm using the Form Helper and the paperclip gem to add file attachments.

rails 文档 警告表单助手不起作用对于 AJAX 文件上传:

The rails docs warn that the Form Helper does not work for AJAX file uploads:

与其他表单不同,制作异步文件上传表单并不像简单的为 form_for 提供 remote: true.使用 Ajax 形式序列化由运行在浏览器中的 JavaScript 完成,并且因为 JavaScript 无法从您的硬盘驱动器读取文件无法上传.最常见的解决方法是使用隐形作为表单提交目标的 iframe.

Unlike other forms making an asynchronous file upload form is not as simple as providing form_for with remote: true. With an Ajax form the serialization is done by JavaScript running inside the browser and since JavaScript cannot read files from your hard drive the file cannot be uploaded. The most common workaround is to use an invisible iframe that serves as the target for the form submission.

显然没有现成的解决方案.所以我想知道什么是最聪明的做法.好像我有几个选择:

It seems clear there's no off-the-shelf solution. So I'm wondering what's the smartest thing to do. Seems like I have several options:

  1. 使用表单助手和 iframe 技巧.
  2. 使用表单助手 + 加载 jQuery 表单插件来提交文件(不确定这是否与 Rails 的真实性令牌等配合得很好)
  3. 使用表单助手 + 回形针 + [其他一些 gem] 扩展其功能以允许 AJAX 表单提交.

这三个似乎都有可能.我对 #3 了解最少,特别是 [其他一些宝石] 部分.我发现了两个类似的问题(thisthis) 中提到了一个名为 Uploadify 的 Pic-Upload 分支,但这些都已经 2 岁了,并且处理 Rails 2 和 3(并且 Uploadify 多年未更新).因此,考虑到发生了多少变化,我认为这确实是一个全新的问题:

All three seem possible. I know the least about #3, specifically the [some other gem] part. I found two similar questions (this and this) which mention a branch of Pic-Upload called Uploadify but those are both 2 years old and deal with Rails 2 and 3 (and Uploadify hasn't been updated in years). So given how much has changed, I think this is really a whole new question:

在 Rails 4 中使用 AJAX 上传文件的最佳方式是什么?

What's the best way to upload files with AJAX in Rails 4?

推荐答案

查看 remotipart gem:https://github.com/JangoSteve/remotipart -- 只需很少的工作就可以让你一路走好!

Have a look into the remotipart gem: https://github.com/JangoSteve/remotipart -- may get you all of the way there with very little work!

这篇关于Rails 4:如何使用 AJAX 上传文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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