all files / src/ FileUpload.vue

10% Statements 3/30
0% Branches 0/18
16.67% Functions 1/6
6.9% Lines 2/29
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76                                                                                                                                                     
// <template>
//   <input type="file" name="fileUpload" @change="onFileChange">
// </template>
//
// <script type="text/babel">
export default {
  name: 'fileupload',
  props: {
    target: {
      type: String
    },
    action: {
      type: String
    }
  },
  data () {
    return {
      file: null
    }
  },
  methods: {
    emitter (event, data) {
      this.$emit(event, data)
    },
    updateProgress (oEvent) {
      let vm = this
      if (oEvent.lengthComputable) {
        let percentComplete = Math.round(oEvent.loaded * 100 / oEvent.total)
        vm.emitter('progress', percentComplete)
      } else {
        // Unable to compute progress information since the total size is unknown
        vm.emitter('progress', false)
      }
    },
    onFileChange (e) {
      let vm = this
 
      if (!this.target || this.target === '') {
        console.log('Please provide the target url')
      } else if (!this.action || this.action === '') {
        console.log('Please provide file upload action ( POST / PUT )')
      } else if (this.action !== 'POST' && this.action !== 'PUT') {
        console.log('File upload component only allows POST and PUT Actions')
      } else {
        let files = e.target.files || e.dataTransfer.files
 
        if (!files.length) {
          return
        };
 
        /*global FormData XMLHttpRequest:true*/
        /*eslint no-undef: "error"*/
 
        this.file = files[0]
        let formData = new FormData()
        formData.append('file', this.file)
 
        var xhr = new XMLHttpRequest()
        xhr.open(this.action, this.target)
 
        xhr.onloadstart = function (e) {
          vm.emitter('start', e)
        }
        xhr.onloadend = function (e) {
          vm.emitter('finish', e)
        }
        xhr.upload.onprogress = vm.updateProgress
        xhr.send(formData)
      }
    }
  }
}
// </script>
/* generated by vue-loader */