Created
January 14, 2021 14:40
-
-
Save hawkeye64/7c6afb5f3236b0c07b82a4963ae593f8 to your computer and use it in GitHub Desktop.
json to formdata
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildFormData (formData, data, parentKey) { | |
if (data && typeof data === 'object' && !(data instanceof Date) && !(data instanceof File)) { | |
Object.keys(data).forEach(key => { | |
buildFormData(formData, data[key], parentKey ? `${parentKey}[${key}]` : key) | |
}) | |
} | |
else { | |
const value = data == null ? '' : data | |
formData.append(parentKey, value) | |
} | |
} | |
function jsonToFormData (data) { | |
const formData = new FormData() | |
buildFormData(formData, data) | |
return formData | |
} | |
export function saveSubmission (context, data) { | |
return new Promise((resolve, reject) => { | |
// this data needs to be formdata for images | |
const formData = jsonToFormData(data) | |
return axios.post( | |
'/api/v1/cart/save-submission', | |
formData, | |
{ | |
headers: { | |
'Content-Type': 'multipart/form-data' | |
} | |
} | |
) | |
.then(results => { | |
resolve(results) | |
}) | |
.catch(error => { | |
console.log(JSON.stringify(error)) | |
reject(error) | |
}) | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment