0

I'm working on a complex app so I simplify my question.

I have a input component located in the InputFile.vue and a FormFile.vue. I import the InputFile into the Form and after the user uploads a file to the inputfield and send the post request, I want to send the file with axios to the backend.

<!--INPUTFILE-->
<template>
  <input
    :id="props.name"
    :name="props.name"
    type="file"
    :ref="props.name"
  />
</template>
// ...

<script setup>
import { defineProps, ref } from "vue";
const props = defineProps({
  name: String,
});
let fileName = ref("");
<!-- FORMFILE -->

<template>
<div>
  <InputFile name="file" />
</div>
</template>

// ...
<script setup>
import InputFile from "@/components/InputFile";
import { ref } from "vue";

const input_file = InputFile.fileName;

  axios.post('post/file', {
    input_file: input_file
  }).then((res) => console.log(res));

The input_file is not getting the value of the file input (from component InputFile.vue). How can I access the input.value from FormFile ?

1 Answer 1

0

You need to handle the file upload via a method.

A Vue method is an object associated with the Vue instance. Functions are defined inside the methods object. Methods are useful when you need to perform some action with v-on directive on an element to handle events.

    <template>
        <input
            v-on:change="handleFileUpload($event)"
            :id="props.name"
            :name="props.name"
            type="file"
            :ref="props.name"
        />
    </template>
    <script>
    export default {
...
        methods: {
            handleFileUpload(e) {
                e.preventDefault();
                const formData = new FormData();
                formData.append('file', e.target.files[0]);
                axios.post('post/file',
                    formData,
                    {
                        headers: {
                            'Content-Type': 'multipart/form-data'
                        },
                    }
                ).then((res) => console.log(res));
            }
        }
    }
    </script>
Sign up to request clarification or add additional context in comments.

2 Comments

Ok and then I can trigger the handleFileUpload method from InputFile.vue in the FormFile.vue?
This answer should help you: stackoverflow.com/questions/40957008/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.