Uploader.vue 1.68 KB
Newer Older
Anton's avatar
Anton committed
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
<template lang="pug">
  q-uploader(dark, auto-expand, clearable, :extensions="ext", :multiple="allowMultiple", :url="url", :headers="reqHeaders",
    :additional-fields="addFields", @add="onSelect", @uploaded="onUploaded", @fail="onFail", @start="onStart", @finish="onFinish")
</template>

<script>
  import { ObjectUtil } from 'mbjs-utils'
  export default {
    data () {
      return {
        ext: this.allowed || undefined,
        allowMultiple: this.multiple || false,
        addFields: this.fields || [],
        responses: {},
        reqHeaders: this.headers || {}
      }
    },
    props: ['url', 'allowed', 'headers', 'multiple', 'fields'],
    watch: {
      allowed () {
        this.ext = this.allowed
      },
      headers () {
        this.reqHeaders = this.headers
      },
      multiple () {
        this.allowMultiple = this.multiple
      },
      fields () {
        this.addFields = this.fields || []
      }
    },
    methods: {
      onSelect (files) {
        this.$emit('select', files)
      },
      onUploaded (file, xhr) {
        let response
        try {
          response = JSON.parse(xhr.responseText)
        }
        catch (e) { /* ignored */ }
        this.responses[ObjectUtil.slug(file.name)] = response
      },
      onFail (file, xhr) {
        let response
        console.debug('uploader failed file', file, xhr)
        try {
          response = JSON.parse(xhr.responseText)
        }
        catch (e) { /* ignored */ }
        this.responses[ObjectUtil.slug(file.name)] = response
      },
      onStart () {
        this.responses = []
        this.$emit('start')
      },
      onFinish () {
        this.$emit('finish', this.responses)
      }
    }
  }
</script>