文系大学生がエンジニアを目指すブログ

Qiitaに書くまでもないメモ的な存在

carrierwaveのテンプレ

いまさらながらだが、、、一応rails5

Gemfile

gem 'carrierwave'
gem 'rmagick'

controler

$ rails g uploader image

app/uploaders/image_uploader.rbが作成される

$ rails g controller image

app/controllers/images_controller.rbが作成される

modle

$ rails g model image --skip-migaration
      invoke  active_record
      create    app/models/image.rb
      invoke    test_unit
      create      test/models/image_test.rb
      create      test/fixtures/images.yml

DB

ridgepoleなのでSchemafileに

create_table "images", force: true do |t|
  t.string "path"
  t.datetime "created_at"
  t.datetime "updated_at"
end

を追加してridgepoleコマンド

準備終了

ここまでで一通りファイル作ったからあとは書くだけ

app/models/image.rb

class Image < ApplicationRecord
  mount_uploader :path, ImageUploader
end

app/controllers/images_controller.rb

class ImagesController < ApplicationController
  def upload
    image = Image.create(path: params[:file])
    respond_to do |format|
      format.html { render json: {path: image.path.url}}
      format.json { render json: {path: image.path.url}}
    end
  end
end

config/routes.rb

post '/image/upload' => 'images#upload'

app/views/topics/_form.html.erb

$(document).on 'turbolinks:load', ->
  $('input.js-upload-image').on 'change', ->
    fileList = @files
    i = 0
    l = fileList.length
    while l > i
      fileReader = new FileReader
      fileReader.onload = ->
        dataUri = @result
        return
      fileReader.readAsDataURL fileList[i]
      i++

    formData = new FormData
    formData.append 'file', $('input.js-upload-image')[0].files[0]
    jQuery.each $('input.js-upload-image')[0].files, (i, file) ->
    $.ajax
      url: '/image/upload'
      type: 'POST'
      data: formData
      cache: false
      processData: false
      contentType: false
      context: this
      success: (msg) ->
        msg = JSON.parse(msg)
        domains = msg.path.split('/')
        filename = domains[domains.length - 1]
        hostname = window.location.origin
        console.log hostname + msg.path
        $('input#office_thumb').val hostname + msg.path
        return
    return

app/assets/javascript/topics.coffee

<div class="form-group">
  <%= form_tag image_upload_path, multipart: true do %>
  <%= file_field_tag 'image', class: 'js-upload-image' %>
  <% end %>
</div>