LoginSignup
19

More than 5 years have passed since last update.

posted at

updated at

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

現象

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

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
What you can do with signing up
19