I'm currently using Vue JS to save a form with ajax and post the data.
var data = JSON.stringify(vm.data);
I want to include file uploads in the same request. I have come across examples using FormData
, but none show how to add files while still posting the existing data together in one request.
I know that individual fields can be added using formData.append(name, value);
, but this only handles one value at a time. The data object I am sending is an array of objects and includes child objects as well.
Is there a way to append the entire data object at once, or do I need to iterate through each item and append them individually?
EDIT - Current 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 }
}