parsePostForm.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. /**
  2. * Licensed to the Apache Software Foundation (ASF) under one
  3. * or more contributor license agreements. See the NOTICE file
  4. * distributed with this work for additional information
  5. * regarding copyright ownership. The ASF licenses this file
  6. * to you under the Apache License, Version 2.0 (the
  7. * "License"); you may not use this file except in compliance
  8. * with the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing,
  13. * software distributed under the License is distributed on an
  14. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15. * KIND, either express or implied. See the License for the
  16. * specific language governing permissions and limitations
  17. * under the License.
  18. */
  19. /**
  20. * Parse multipart form data sent via POST requests.
  21. */
  22. export default function parsePostForm(requestBody: ArrayBuffer) {
  23. type ParsedFields = Record<string, string[] | string>;
  24. if (requestBody.constructor.name !== 'ArrayBuffer') {
  25. return requestBody;
  26. }
  27. const lines = new TextDecoder('utf-8').decode(requestBody).split('\n');
  28. const fields: ParsedFields = {};
  29. let key = '';
  30. let value: string[] = [];
  31. function addField(key: string, value: string) {
  32. if (key in fields) {
  33. if (Array.isArray(fields[key])) {
  34. (fields[key] as string[]).push(value);
  35. } else {
  36. fields[key] = [fields[key] as string, value];
  37. }
  38. } else {
  39. fields[key] = value;
  40. }
  41. }
  42. lines.forEach(line => {
  43. const nameMatch = line.match(/Content-Disposition: form-data; name="(.*)"/);
  44. if (nameMatch) {
  45. if (key) {
  46. addField(key, value.join('\n'));
  47. }
  48. key = nameMatch[1];
  49. value = [];
  50. } else if (!/----.*FormBoundary/.test(line)) {
  51. value.push(line);
  52. }
  53. });
  54. if (key && value) {
  55. addField(key, value.join('\n'));
  56. }
  57. return fields;
  58. }