formDataToBlob.js 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. import utils from '../utils.js';
  2. const CRLF = '\r\n';
  3. const normalizeLines = (value) => String(value).replace(/\r\n|\r|\n/g, CRLF);
  4. const escapeName = (value) =>
  5. String(value).replace(/[\r\n"]/g, (char) =>
  6. char === '\r' ? '%0D' : char === '\n' ? '%0A' : '%22'
  7. );
  8. // Count UTF-8 bytes without allocating an encoded copy of a field. FormData
  9. // string values normalize line endings; Blob/File contents remain unchanged.
  10. const stringBytes = (value, normalize) => {
  11. let length = 0;
  12. for (let i = 0; i < value.length; i++) {
  13. const code = value.charCodeAt(i);
  14. if (normalize && (code === 13 || code === 10)) {
  15. if (code === 13 && value.charCodeAt(i + 1) === 10) i++;
  16. length += 2;
  17. } else if (code < 0x80) {
  18. length++;
  19. } else if (code < 0x800) {
  20. length += 2;
  21. } else if (
  22. code >= 0xd800 &&
  23. code <= 0xdbff &&
  24. value.charCodeAt(i + 1) >= 0xdc00 &&
  25. value.charCodeAt(i + 1) <= 0xdfff
  26. ) {
  27. length += 4;
  28. i++;
  29. } else {
  30. length += 3;
  31. }
  32. }
  33. return length;
  34. };
  35. // Describe serialization failures independently of any request library.
  36. export class FormDataError extends TypeError {
  37. constructor(message, reason) {
  38. super(message);
  39. this.name = 'FormDataError';
  40. this.reason = reason;
  41. }
  42. }
  43. // The caller supplies the boundary, Blob implementation, and limit error.
  44. export default function formDataToBlob(form, Blob, limit, limitError, boundary) {
  45. if (!utils.isFunction(Blob)) {
  46. throw new FormDataError('Blob is not supported', 'blob');
  47. }
  48. if (
  49. !utils.isString(boundary) ||
  50. !/^[A-Za-z0-9'()+_,./:=? -]{1,70}$/.test(boundary) ||
  51. / $/.test(boundary)
  52. ) {
  53. throw new FormDataError('Invalid multipart boundary', 'boundary');
  54. }
  55. const footer = '--' + boundary + '--' + CRLF;
  56. let length = footer.length;
  57. const parts = [];
  58. const checkLength = (extra) => {
  59. if (length + extra > limit) throw limitError();
  60. };
  61. checkLength(0);
  62. for (const [name, value] of form) {
  63. const isString = utils.isString(value);
  64. const valueLength = isString ? stringBytes(value, true) : value.size;
  65. if (!Number.isFinite(valueLength) || valueLength < 0) {
  66. throw new FormDataError('Unsupported FormData part size', 'part');
  67. }
  68. // Reject large values and names before building normalized header strings.
  69. checkLength(
  70. valueLength +
  71. stringBytes(name, true) +
  72. (!isString && value.name ? stringBytes(value.name, false) : 0) +
  73. (!isString && value.type ? stringBytes(value.type, false) : 0)
  74. );
  75. let header =
  76. '--' +
  77. boundary +
  78. CRLF +
  79. 'Content-Disposition: form-data; name="' +
  80. escapeName(normalizeLines(name)) +
  81. '"';
  82. if (!isString) {
  83. header +=
  84. '; filename="' +
  85. escapeName(utils.isString(value.name) ? value.name : 'blob') +
  86. '"' +
  87. CRLF +
  88. 'Content-Type: ' +
  89. String(value.type || 'application/octet-stream').replace(/[\r\n]/g, '');
  90. }
  91. header += CRLF + CRLF;
  92. const partLength = stringBytes(header, false) + valueLength + CRLF.length;
  93. checkLength(partLength);
  94. length += partLength;
  95. parts.push({ header, value, isString });
  96. }
  97. // Native Blob composition retains existing Blob/File data. No file is read
  98. // and no complete multipart ArrayBuffer is created to determine its length.
  99. const blobParts = [];
  100. for (const part of parts) {
  101. blobParts.push(part.header, part.isString ? normalizeLines(part.value) : part.value, CRLF);
  102. }
  103. blobParts.push(footer);
  104. return new Blob(blobParts, { type: 'multipart/form-data; boundary=' + boundary });
  105. }