Help us understand the problem. What is going on with this article?

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

More than 1 year has passed since last update.

現象

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away