UploadFiles.vue 2.4 KB
<template>
  <div>
    <v-text-field
      :placeholder="label"
      @click="clickInputTag"
      v-model="fileName"
      append-icon="attach_file"
    ></v-text-field>
    <input
      type="file"
      style="display: none"
      :id="id"
      :ref="reference"
      accept="image/*"
      @change="convertToBase64()"
    />
  </div>
</template> 
    <script >
export default {
  props: ["label", "reference", "id", "trigger"],
  data() {
    return {
      fileToLoad: "",
      fileName: "",
      fileInBase64: ""
    };
  },
  methods: {
    clickInputTag() {
      document.getElementById(this.id).click();
    },
    convertToBase64(e) {
      //Read File
      var selectedFile = document.getElementById(this.id).files;
      //Check File is not Empty

      if (selectedFile.length > 0) {
        // Select the very first file from list
        this.fileToLoad = selectedFile[0];
        this.fileName = selectedFile[0].name;
        // FileReader function for read the file.
        var fileReader = new FileReader();
        // Onload of file read the file content
        let vm = this;
        fileReader.onload = function(fileLoadedEvent) {
          vm.fileInBase64 = fileLoadedEvent.target.result;

          var str = vm.fileInBase64;
          const [baseUrl, requiredUrl] = str.split(/,/);

          let fileData = {
            fileName: this.fileName,
            fileInBase64: requiredUrl,
            trigger: ""
          };
          vm.$emit("fileSelected", fileData);
        };

        // Convert data to base64
        fileReader.readAsDataURL(this.fileToLoad);
      }
    },
    resetInput(params) {
      // RESET INPUT ELEMENT,fileName and selectedfile array
      this.fileToLoad = null;
      this.fileName = null;
      this.fileInBase64 = null;
      let inputTag = document.getElementById(this.id);
      inputTag.value = null;
      // inputTag.type = "text";
      // inputTag.type = "file";

      let fileData = {
        fileName: this.fileName,
        fileInBase64: this.fileInBase64,
        trigger: ""
      };
      this.$emit("fileSelected", fileData);
    }
  },
  watch: {
    respondToTrigger() {
      if (this.respondToTrigger == "reset") {
        this.resetInput();
      }
    }
  },
  computed: {
    respondToTrigger: {
      get() {
        return this.trigger;
      },
      set(newVal) {}
      // this.respondToTrigger = this.trigger;
    }
  }
};
</script> 
    <style scoped >
</style>