isuke
9/29/2016 - 12:51 PM

file post by vue.js

file post by vue.js

$ ->
  Vue.component 'file-new',
    template: '#file_new'
    data: ->
      file_input: undefined
      files: undefined
    methods:
      fileInputChange: (e) ->
        @file_input = e.target
        @files = @file_input.files
      fileUpload: ->
        return if @files.length <= 0
        $.each Array.prototype.slice.call(@files, 0), (i, file) =>
          @_handleUpload(file)
        @file_input.value = ''
      _handleUpload: (file) ->
        form = new FormData()
        form.append('Content-Type', file.type || 'application/octet-stream')
        form.append('file', file)

        $.ajax
          url: "/api/hoge.json"
          type: 'POST'
          data: form
          cache: false
          contentType: false
          processData: false
        .done (response) =>
          console.log response
        .fail (response) =>
          console.error response
template#file_new
  = file_field_tag :files, multiple: true, 'v-on:change' => 'fileInputChange'
  = submit_tag 'Upload', 'v-on:click.prevent' => 'fileUpload'