N
N
noob_NOOB2019-06-21 20:35:49
Vue.js
noob_NOOB, 2019-06-21 20:35:49

How to upload an image in a form via Vue without submitting the form itself?

I have a form with many fields. There is an input for loading an image. I want to implement image uploading through Vue so that I can immediately display the thumbnail of the uploaded image, before submitting the completed form.

There is this component:

export default {
        name: "upload-image",
        props: [
            'result',
            'sizes'
        ],
        data: function() {
            return {
                files: []
            }
        },
        methods: {
            onFileChange: function(e) {
                let files = e.target.files || e.dataTransfer.files;
                if (!files.length)
                    return;
                this.createImage(files[0]);
            },
            createImage: function(file) {
                let reader = new FileReader();
                let vm = this;
                reader.onload = function(e) {
                    vm.image = e.target.result;
                };
                reader.readAsDataURL(file);
               
            },
            upload: function(){
                let data = new FormData();
                let that = this;

                data.append('file', this.image);
                data.append('sizes', this.sizes);
                data.append('root', 'uploads/test');

                axios.post('/api/photo/upload-base64', data)
                    .then(function(res) {
                        let result_input = document.querySelector('input[name=' + that.result + ']');
                        let data = res['data'];
                        result_input.value = data['path'];
                    });

            }
        }
    }


The component template looks like this:
<template>
    <div class="d-flex flex-row align-items-center" style="height: 100%;">
        <div class="card d-flex" style="width: 100%">
            <div class="card-body">
                <input type="file" accept="image/jpeg, image/gif, image/png" id="upload-file"  @change="onFileChange"/>
                <button @click="upload" class="btn btn-primary btn-block mt-4">Загрузить</button>
            </div>
        </div>
    </div>
</template>


The component is simply inserted into the original form.

The problem is that after receiving a response from the server and processing the axios promise, the entire form is automatically submitted. How can I implement file upload without sending the form itself and crutches?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2019-06-21
@noob_NOOB

Cancel the default action when the button is clicked: @click.prevent="upload".

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question