upload.vue 1.8 KB
Newer Older
1
<script>
2
  import { mapActions, mapState } from 'vuex';
3 4 5

  export default {
    props: {
6
      branchId: {
7 8 9
        type: String,
        required: true,
      },
10 11 12 13 14 15 16 17 18 19
      parent: {
        type: Object,
        default: null,
      },
    },
    computed: {
      ...mapState([
        'trees',
        'currentProjectId',
      ]),
20 21
    },
    methods: {
22 23 24
      ...mapActions([
        'createTempEntry',
      ]),
25 26 27 28 29 30 31 32
      createFile(target, file, isText) {
        const { name } = file;
        let { result } = target;

        if (!isText) {
          result = result.split('base64,')[1];
        }

33 34
        this.createTempEntry({
          name,
35 36 37
          projectId: this.currentProjectId,
          branchId: this.branchId,
          parent: this.parent,
38 39 40
          type: 'blob',
          content: result,
          base64: !isText,
41
        });
42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
      },
      readFile(file) {
        const reader = new FileReader();
        const isText = file.type.match(/text.*/) !== null;

        reader.addEventListener('load', e => this.createFile(e.target, file, isText), { once: true });

        if (isText) {
          reader.readAsText(file);
        } else {
          reader.readAsDataURL(file);
        }
      },
      openFile() {
        Array.from(this.$refs.fileUpload.files).forEach(file => this.readFile(file));
      },
58 59 60
      startFileUpload() {
        this.$refs.fileUpload.click();
      },
61 62 63 64 65 66 67 68 69 70 71
    },
    mounted() {
      this.$refs.fileUpload.addEventListener('change', this.openFile);
    },
    beforeDestroy() {
      this.$refs.fileUpload.removeEventListener('change', this.openFile);
    },
  };
</script>

<template>
72 73 74 75 76 77 78 79
  <div>
    <a
      href="#"
      role="button"
      @click.prevent="startFileUpload"
    >
      {{ __('Upload file') }}
    </a>
80 81 82 83 84 85
    <input
      id="file-upload"
      type="file"
      class="hidden"
      ref="fileUpload"
    />
86
  </div>
87
</template>