LoginSignup
22
19

More than 5 years have passed since last update.

RailsでファイルをAjaxで送信する

Last updated at Posted at 2015-02-05

現象

Railsで次のようにしてもajaxできない。

submit.html.haml
= form_tag file_submit_path, multipart: true, remote: true
  = file_field :submit, :file
  = submit_tag

正確に言うと、ajaxにならずに通常のページ遷移をしてしまう。
ファイルのデータは送られている模様。

対処

remotipartっていうgemを使う。
https://github.com/JangoSteve/remotipart

Gemfile
gem 'remotipart'
bundle install
application.js
//= require jquery.remotipart

haml側は特に変えなくてもこれだけで送れるようになる。

Rails 5のとき

コメントでRails 5だとうまく動かないという報告あり。現在調査中。

原因

http://guides.rubyonrails.org/form_helpers.html#dealing-with-ajax
詳しくは上記URLを参照のこと。

要は、Javascriptからはローカルのファイルを読み取れないので、通常のフォームとしてデータを送らないといけないが、フォームでデータを送るとページ遷移となってしまうということ。

22
19
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
19