简体   繁体   English

如何在 vue.js 版本 3 中上传文件

[英]How to upload file in vue.js version 3

I wanted to upload file using vue.js version 3.我想使用 vue.js 版本 3 上传文件。

I can able to import ref but not sure how to use it for fetching file data?我可以导入ref但不确定如何使用它来获取文件数据?

FileUploadTest.vue文件上传测试.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文件上传测试.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 变量中

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

Since you're using the option api you don't need the ref just use this.$refs.file :由于您使用的是选项 api 您不需要ref只需使用this.$refs.file

   onChangeFileUpload() {
        debugger;
        this.file = this.$refs.file[0]; 
    }

Vue3.js upload file to server using composition api Vue3.js 使用组合 api 将文件上传到服务器

<template>
      <input ref="file" v-on:change="handleFileUpload()"  type="file">
</template>
<script>

import { ref} from "vue"

export default{
    name:'Add',

    setup() {
        const file = ref(null)

        const handleFileUpload = async() => {
           // debugger;
            console.log("selected file",file.value.files)
            //Upload to server
        }

        return {
          handleFileUpload,
          file
       }
    }
}

</script>

Here's a simple component you could use for a file upload with the options api.这是一个简单的组件,您可以使用 api 选项进行文件上传。 No ref needed.不需要ref

fileUpload.vue文件上传.vue

<template>
    <input type="file" @change="onChange($event)">
</template>

<script>
export default {
    props: ['modelValue'],
    methods: {
        onChange(event) {
            this.$emit('update:modelValue', event.target.files[0]);
        },
    },
};
</script>

Your component...你的组件...

<template>
    <form novalidate @submit.prevent="onSubmit">
        <file-upload v-model="form.file"></file-upload>
    </form>
</template>

<script>
import fileUpload from 'fileUpload';
export default {
    components: { fileUpload },
    data: () => ({ form: { file: null } }),
    methods: {
        onSubmit() {
            console.log(this.form);
            // post the form to the server
        }
    }
}
</script>

I can summarize the answer as below.我可以将答案总结如下。

FileUpload.vue文件上传.vue

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

FileUpload.ts文件上传.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,
        }
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM