typescriptvue.jsvuejs3

How to upload file in vue.js version 3


I wanted to upload file using vue.js version 3.

I can able to import ref but not sure how to use it for fetching file data?

FileUploadTest.vue

<template>
<h1>File Upload</h1>
<div class="container">
    <div>
      <label>File
        <input type="file" id="file" ref="file" v-on:change="onChangeFileUpload()"/>
      </label>
        <button v-on:click="submitForm()">Upload</button>
    </div>
  </div>
</template>

<script src="./FileUploadTest.ts" lang="ts"></script>

FileUploadTest.ts

import { Options, Vue } from "vue-class-component";
import { ref } from 'vue';
import axios from "../../axios/index";

@Options({})
export default class FileUploadTest extends Vue {

    protected file: any;

    submitForm() {
        const formData = new FormData();
        formData.append('bytes', this.file);

        axios.post('https://localhost:44313/api/app/file/save',
            formData,
            {
                headers: {
                    'Content-Type': 'multipart/form-data'
                }
            }
        ).then(function (data) {
            console.log(data.data);
        })
        .catch(function () {
            console.log('FAILURE!!');
        });
    }

    onChangeFileUpload() {
        debugger;
        this.file = ref(["file"]).value; 
    }
};

The actual file content is not storing in the this.file variable

this.file = ref(["file"]).value; 

Solution

  • I can summarize the answer as below.

    FileUpload.vue

    <template>
      <div>
        <input
          type="file"
          @change="onFileChanged($event)"
          accept="image/*"
          capture
        />
      </div>
    </template>
    

    FileUpload.ts

    import { defineComponent, ref } from "vue";
    
    export default defineComponent({
    
        name: "FileUpload",
    
        setup() {
            const file = ref<File | null>();
            const form = ref<HTMLFormElement>();
    
            function onFileChanged($event: Event) {
                const target = $event.target as HTMLInputElement;
                if (target && target.files) {
                    file.value = target.files[0];
                }
            }
    
            async function saveImage() {
                if (file.value) {
                    try {
                    // save file.value
                    } catch (error) {
                        console.error(error);
                        form.value?.reset();
                        file.value = null;
                    } finally {
                    }
                }
            };
    
            return {
                saveImage,
                onFileChanged,
            }
        }
    });