1 | |
2 | type Box = { |
3 | token: string; |
4 | }; |
5 | type Base64 = string; |
6 | |
7 | * Upload file |
8 | * Uploads a small file to Box. For file sizes over 50MB we recommend |
9 | using the Chunk Upload APIs. |
10 |
|
11 | The `attributes` part of the body must come **before** the |
12 | `file` part. Requests that do not follow this format when |
13 | uploading the file will receive a HTTP `400` error with a |
14 | `metadata_after_file_contents` error code. |
15 | */ |
16 | export async function main( |
17 | auth: Box, |
18 | fields: string | undefined, |
19 | content_md5: string, |
20 | body: { |
21 | attributes: { |
22 | name: string; |
23 | parent: { id: string }; |
24 | content_created_at?: string; |
25 | content_modified_at?: string; |
26 | }; |
27 | file: { |
28 | base64: Base64; |
29 | type: |
30 | | "image/png" |
31 | | "image/jpeg" |
32 | | "image/gif" |
33 | | "application/pdf" |
34 | | "appication/json" |
35 | | "text/csv" |
36 | | "text/plain" |
37 | | "audio/mpeg" |
38 | | "audio/wav" |
39 | | "video/mp4"; |
40 | name: string; |
41 | }; |
42 | }, |
43 | ) { |
44 | const url = new URL(`https://api.box.com/2.0/files/content`); |
45 | for (const [k, v] of [["fields", fields]]) { |
46 | if (v !== undefined && v !== "" && k !== undefined) { |
47 | url.searchParams.append(k, v); |
48 | } |
49 | } |
50 | const formData = new FormData(); |
51 | for (const [k, v] of Object.entries(body)) { |
52 | if (v !== undefined) { |
53 | if (["file"].includes(k)) { |
54 | const { base64, type, name } = v as { |
55 | base64: Base64; |
56 | type: string; |
57 | name: string; |
58 | }; |
59 | formData.append( |
60 | k, |
61 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
62 | type, |
63 | }), |
64 | name, |
65 | ); |
66 | } else { |
67 | formData.append(k, String(v)); |
68 | } |
69 | } |
70 | } |
71 | const response = await fetch(url, { |
72 | method: "POST", |
73 | headers: { |
74 | "content-md5": content_md5, |
75 | Authorization: "Bearer " + auth.token, |
76 | }, |
77 | body: formData, |
78 | }); |
79 | if (!response.ok) { |
80 | const text = await response.text(); |
81 | throw new Error(`${response.status} ${text}`); |
82 | } |
83 | return await response.json(); |
84 | } |
85 |
|