toFormData.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. 'use strict';
  2. function combinedKey(parentKey, elKey) {
  3. return parentKey + '.' + elKey;
  4. }
  5. function buildFormData(formData, data, parentKey) {
  6. if (Array.isArray(data)) {
  7. data.forEach(function buildArray(el, i) {
  8. buildFormData(formData, el, combinedKey(parentKey, i));
  9. });
  10. } else if (
  11. typeof data === 'object' &&
  12. !(data instanceof File || data === null)
  13. ) {
  14. Object.keys(data).forEach(function buildObject(key) {
  15. buildFormData(
  16. formData,
  17. data[key],
  18. parentKey ? combinedKey(parentKey, key) : key
  19. );
  20. });
  21. } else {
  22. if (data === undefined) {
  23. return;
  24. }
  25. var value =
  26. typeof data === 'boolean' || typeof data === 'number'
  27. ? data.toString()
  28. : data;
  29. formData.append(parentKey, value);
  30. }
  31. }
  32. /**
  33. * convert a data object to FormData
  34. *
  35. * type FormDataPrimitive = string | Blob | number | boolean
  36. * interface FormDataNest {
  37. * [x: string]: FormVal
  38. * }
  39. *
  40. * type FormVal = FormDataNest | FormDataPrimitive
  41. *
  42. * @param {FormVal} data
  43. */
  44. module.exports = function getFormData(data) {
  45. var formData = new FormData();
  46. buildFormData(formData, data);
  47. return formData;
  48. };