LoginSignup
14
11

More than 5 years have passed since last update.

file_fieldでファイルを自動で送信する

Last updated at Posted at 2018-04-15

form_forのfile_fieldで
・ファイル選択後、submitボタンを押さずに自動で送信したい
・ファイル選択ボタンを自由に変更したい
と思って調べた結果、viewを下記のようにしたら上手くいった。

show.html.erb
<%= form_for @user, :url => change_image_users_path, :html => {method: 'PATCH'} do |f| %>
    <%= f.label :image, :class => "ignore" %>
    <label for="user_image" class="square_btn">
       画像選択
       <%= f.file_field :image, :class => "ignore" %>
    </label>
<% end %>
<script type="text/javascript">
    $('input[type=file]').on('change', function (e) {
        console.log(e.target.files);
        if (e.target.files[0].size > 0) {
            $(this).parents('form').submit();
        }
    });
</script>
user.scss
.ignore {
    display:none;
}

.square_btn {
    position: relative;
    display: inline-block;
    padding: 0.25em 0.5em;
    text-decoration: none;
    color: #FFF;
    background: #03A9F4;/*色*/
    border: solid 1px #0f9ada;/*線色*/
    border-radius: 4px;
    box-shadow: inset 0 1px 0 rgba(255,255,255,0.2);
    text-shadow: 0 1px 0 rgba(0,0,0,0.2);
    cursor : pointer;
}

下記を参考にさせて頂きました。

form_forのfile_fieldで画像を選択したと同時に送信する方法
https://teratail.com/questions/62061

input type="file"のボタンデザインを変更する方法
http://proengineer.internous.co.jp/content/columnfeature/7605

CSSで作る!押したくなるボタンデザイン100(Web用)
https://saruwakakun.com/html-css/reference/buttons

[2018/5/15追記]
画像選択後の下記は不要でしたので、削除致しました。

show.html.erb
<script type="text/javascript" src="//code.jquery.com/jquery-3.1.1.min.js"></script>

※上記が記載されていると、別のjQueryが動作しなくなる可能性があります。
申し訳ございませんでした。

14
11
0

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
14
11