banky
banky

Reputation: 848

How to append files and data to FormData in 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?

Upvotes: 6

Views: 60580

Answers (2)

samayo
samayo

Reputation: 16495

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 => {

      }
    )
  }
}

Upvotes: 20

Alex
Alex

Reputation: 1375

Here is solution for multiply files uploading. Don't forget to add unique id for every formData object.

<input type="file" multiple :disabled="isSaving" @change="filesChange($event.target.files)" accept="your_format_here" class="input-file">

And here is axios method and creating of our formData object.

  methods: {
    async save(datafile) {
      // upload data to the server
      return await axios.post(
          store.state.endpoints.baseURL + "upload/url/",
          datafile, {
            headers: {
              Authorization: 'Bearer ' + store.state.jwt
            }
          }
        )
        .then(response => {
          console.log(response)
        })
        .catch(err => {
          console.log(err.response)
        });
    },
    filesChange(fileList) {
      const formData = new FormData();
      if (!fileList.length) return;
      for (var i = 0; i < fileList.length; i++) {
        let file = fileList[i];
        // Here we create unique key 'files[i]' in our response dict
        formData.append('files[' + i + ']', file);
      }
      this.save(formData);
    }
  },

Upvotes: 2

Related Questions