Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to append files and data to FormData in vue.js

Tags:

vue.js

I'm trying to append uploaded file and a data value to FormData in vue.js. In my controller, only the files request can be assessed.

data() {
  return (
    file: '',
    categ: ''
  }
}

And in my method:

var form = new FormData();
var file = this.file;
var cat = this.categ;
form.append('pics', file, cat);

axios.post('/api', form, { headers:
  { 'Content-Type': 'multipart/form-data' }
}).then (res => console.log(res));  

What am I doing wrong?

like image 431
banky Avatar asked Dec 02 '22 10:12

banky


1 Answers

The problem is how you are probably getting the file from the input.

If your input looks like this:

<input type="file"  @change="upload($event)" id="file-input">

Then you see an use the $event to get the file and use it as:

methods: {
  upload(event){
    let data = new FormData();
    let file = event.target.files[0];

    data.append('name', 'my-file')
    data.append('file', file)

    let config = {
      header : {
       'Content-Type' : 'multipart/form-data'
     }
    }

    axios.post('/api', data, config).then(
      response => {

      }
    )
  }
}
like image 171
samayo Avatar answered Dec 04 '22 07:12

samayo