({localPath, url, options, log}: HttpUploadRequest)
| 63 | |
| 64 | /** Uploads the file as a multipart form or a raw request body */ |
| 65 | export async function uploadFileToHttp({localPath, url, options, log}: HttpUploadRequest): Promise<void> { |
| 66 | const { |
| 67 | method = 'POST', |
| 68 | timeout = DEFAULT_TIMEOUT_MS, |
| 69 | headers, |
| 70 | auth, |
| 71 | fileFieldName = DEFAULT_FILE_FIELD_NAME, |
| 72 | formFields, |
| 73 | } = options; |
| 74 | const {href} = url; |
| 75 | |
| 76 | const requestOpts: RawAxiosRequestConfig = { |
| 77 | url: href, |
| 78 | method, |
| 79 | timeout, |
| 80 | maxContentLength: Infinity, |
| 81 | maxBodyLength: Infinity, |
| 82 | }; |
| 83 | const axiosAuth = toAxiosAuth(auth); |
| 84 | if (axiosAuth) { |
| 85 | requestOpts.auth = axiosAuth; |
| 86 | } |
| 87 | if (fileFieldName) { |
| 88 | // Native FormData/Blob; axios' Node adapter builds the multipart stream itself for any |
| 89 | // spec-compliant FormData, so the `form-data` package is not needed. |
| 90 | const form = new FormData(); |
| 91 | if (formFields) { |
| 92 | let pairs: [string, unknown][] = []; |
| 93 | if (Array.isArray(formFields)) { |
| 94 | pairs = formFields as [string, unknown][]; |
| 95 | } else if (isPlainObject(formFields)) { |
| 96 | pairs = Object.entries(formFields); |
| 97 | } |
| 98 | for (const [key, value] of pairs) { |
| 99 | if (key.toLowerCase() === fileFieldName?.toLowerCase()) { |
| 100 | continue; |
| 101 | } |
| 102 | if (typeof value === 'string' || value instanceof Blob) { |
| 103 | form.append(key, value); |
| 104 | } else if (Buffer.isBuffer(value)) { |
| 105 | // Per the WHATWG FormData spec, appending a Blob always produces a *file* part |
| 106 | // (`filename="blob"`) - unlike the old `form-data` package, which sent a Buffer as |
| 107 | // a plain field. There is no native FormData API to send raw bytes as a non-file |
| 108 | // field, so fail loud instead of silently changing the multipart classification. |
| 109 | throw new TypeError( |
| 110 | `formFields.${key}: Buffer values are not supported, because native FormData always sends ` + |
| 111 | `them as file attachments rather than plain fields. Pass a string, or a Blob if a file ` + |
| 112 | `attachment is actually intended.`, |
| 113 | ); |
| 114 | } else { |
| 115 | form.append(key, String(value)); |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | // AWS S3 POST upload requires this to be the last field; do not move before formFields. |
| 120 | const fileName = path.basename(localPath); |
| 121 | const fileType = mimeTypes.lookup(fileName) || undefined; |
| 122 | form.append(fileFieldName, await openAsBlob(localPath, {type: fileType}), fileName); |
no test coverage detected