Search code examples
javascriptajaxvue.jsvuejs2form-data

Upload files with ajax and existing form data


I'm saving a form with ajax that posts data from Vue JS.

var data = JSON.stringify(vm.data);

I wish to upload files in the same request. I've seen a few examples using FormData. However I can't seem to find an example of how to add files and still post the existing data in the same request.

I've seen that specific fields can be added using formData.append(name, value); but this just seems to be one value at a time. The object I'm posting is an array of objects and also contains child objects.

Is it possible to append the complete in one go, or will I have to append each item while iterating through the existing data?

EDIT - Exiting ajax request:

var data = JSON.stringify(vm.data);

me.xhr({
    headers: {'Content-Type': 'multipart/form-data'},
    method: 'PUT',
    url: 'swatch/' + vm.swatch.id + '.json',
    callback: function(res) {
        vm.saving = false;
        try {
            alert(res.message ? res.message : "Swatch saved successfully");
        } catch (e) {
            alert(res.message ? res.message : "Failed to save the changes, please try again.");
        }
    },
    onerror: () => {
        vm.saving = false;
        alert('Failed to save the changes, please try again.');
    },
    data: { swatch: data }
}

Solution

  • you can use FormData in:

    var data = JSON.stringify(vm.data);
    var fd = new FormData();
    fd.append('data',data);
    fd.append('file',vm.fileUploaded);
    
    me.xhr({
    headers: {'Content-Type': 'multipart/form-data'},
    method: 'PUT',
    url: 'swatch/' + vm.swatch.id + '.json',
    callback: function(res) {
        vm.saving = false;
        try {
            alert(res.message ? res.message : "Swatch saved successfully");
        } catch (e) {
            alert(res.message ? res.message : "Failed to save the changes, please try again.");
        }
    },
    onerror: () => {
        vm.saving = false;
        alert('Failed to save the changes, please try again.');
    },
    data: fd
    }
    

    component:

    <input type="file" @onchange="changed($event)">
    
    
    new vue({
    data:{fileUploaded:''},
      methods:{
          changed(event){
               this.fileUploaded = event.target.files[0];
           }
       }
    })