[Vuejs]-How to open browse folder for upload file?

0👍

There are different approaches to doing this. One is to create an area where you can select a file to upload or drag and drop to upload.

<template>
  <div class="file-upload">
    <div
      class="text_field"
      @click="pickFile"
      @drop="uploadFile"
      @dragover.prevent
      @drop.prevent
    >
      <input
        id="file"
        ref="image"
        :accept="allowedFileTypes"
        style="display: none"
        type="file"
        @change="uploadFile"
      />
      <span v-if="fileUploading"> File uploading </span>
      <span v-else> Drag file here or click to upload </span>
    </div>
  </div>
</template>

Script

<script>
export default {
  name: "UploadFile",
  data() {
    return {
      fileUploading: false,
      allowedFileTypes: ".pdf, .jpg, .jpeg, .png, .doc, .docx, .xls, .xlsx, video/*, audio/*",
    };
  },
  methods: {
    pickFile() {
      this.$refs.image.click();
    },
    async uploadFile(e) {
      this.fileUploading = true;
      const files = e.target.files || e.dataTransfer.files;
      if (!files.length) {
        return;
      }
      const file = document.getElementById("file").files[0];
      /* Creating a form element so that it can be detected as req.files (in Node.js, for example) */
      const fileForm = new window.FormData();
      fileForm.append("file", file);
      /* Simulating uploading of files, we wait for two seconds */
      setTimeout(() => {
        this.fileUploading = false;
      }, 2000);
      /* Below, you can make a request to your backend to post the image */
      /* await axios.post('your_upload_file_url', fileForm)
        .then(res => res)
        .catch((error) => Promise.reject(error))
        */
    },
  },
};
</script>

You can add some styles too

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.file-upload {
  border: 1px dashed #007991FF;
  border-radius: 5px;
  height: 192px;
  cursor: pointer;
  text-align: center;
  vertical-align: middle;
  span {
    position: relative;
    top: 75px;
    padding: 20px;
    font-size: 14px;
    color: #cac8c8;
  }
}
</style>

Leave a comment