L
L
lemonlimelike2018-06-29 01:05:30
JavaScript
lemonlimelike, 2018-06-29 01:05:30

How to combine two methods?

uploadImage method:

uploadImage(event) {

          const URL = 'http://foobar.com/upload'; 

          let data = new FormData();
          data.append('name', 'my-picture');
          data.append('file', event.target.files[0]); 

          let config = {
            header : {
              'Content-Type' : 'image/png'
            }
          }

          axios.put(
            URL, 
            data,
            config
          ).then(
            response => {
              console.log('image upload response > ', response)
            }
          )
       }

is responsible for sending the file to the server, here is the input for it:
<input type="file" accept="image/*" @change="uploadImage($event)" id="file-input">

And here is the method for creating the entry:
create: function(){
    				axios.post('/api/crud',{
    					name: this.name,
    					keywords: this.keywords,
    					title: this.name
    				}).then(response =>{
    					console.log(response)
    					location.href = '/crud';
    				}).catch(error =>{
    					console.log(error.response)
    				});
    			}

How to combine these two methods so that they work on a click on one button?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Shahob I, 2018-06-29
@lemonlimelike

<input type="file" accept="image/*" @change="handleChange($event)" id="file-input">
<button v-on:click.prevent="handleSend">Отправить</button>

new Vue({
    el: '#app',
    data: {
        name: 'John Doe',
        keywords: 'key',
        form: new FormData()
    },
    methods: {
        handleSend: function () {
            // upload image
            axios.put(
                '/upload',
                this.form, {
                    header: {
                        'Content-Type': 'image/png'
                    }
                }
            ).then(response => {
                console.log('image upload response > ', response);
            });

            // send form
            axios.post('/api/crud', {
                name: this.name,
                keywords: this.keywords,
                title: this.name
            }).then(response => {
                console.log(response);
            }).catch(error => {
                console.log(error.response);
            });

        },
        handleChange: function (event) {
            this.form.append('name', 'my-picture');
            this.form.append('file', event.target.files[0]);
        },
    }
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question