1 | |
2 | type Box = { |
3 | token: string; |
4 | }; |
5 | type Base64 = string; |
6 | |
7 | * Upload file version |
8 | * Update a file's content. 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 | file_id: string, |
19 | fields: string | undefined, |
20 | if_match: string, |
21 | content_md5: string, |
22 | body: { |
23 | attributes: { name: string; content_modified_at?: string }; |
24 | file: { |
25 | base64: Base64; |
26 | type: |
27 | | "image/png" |
28 | | "image/jpeg" |
29 | | "image/gif" |
30 | | "application/pdf" |
31 | | "appication/json" |
32 | | "text/csv" |
33 | | "text/plain" |
34 | | "audio/mpeg" |
35 | | "audio/wav" |
36 | | "video/mp4"; |
37 | name: string; |
38 | }; |
39 | }, |
40 | ) { |
41 | const url = new URL(`https://api.box.com/2.0/files/${file_id}/content`); |
42 | for (const [k, v] of [["fields", fields]]) { |
43 | if (v !== undefined && v !== "" && k !== undefined) { |
44 | url.searchParams.append(k, v); |
45 | } |
46 | } |
47 | const formData = new FormData(); |
48 | for (const [k, v] of Object.entries(body)) { |
49 | if (v !== undefined) { |
50 | if (["file"].includes(k)) { |
51 | const { base64, type, name } = v as { |
52 | base64: Base64; |
53 | type: string; |
54 | name: string; |
55 | }; |
56 | formData.append( |
57 | k, |
58 | new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], { |
59 | type, |
60 | }), |
61 | name, |
62 | ); |
63 | } else { |
64 | formData.append(k, String(v)); |
65 | } |
66 | } |
67 | } |
68 | const response = await fetch(url, { |
69 | method: "POST", |
70 | headers: { |
71 | "if-match": if_match, |
72 | "content-md5": content_md5, |
73 | Authorization: "Bearer " + auth.token, |
74 | }, |
75 | body: formData, |
76 | }); |
77 | if (!response.ok) { |
78 | const text = await response.text(); |
79 | throw new Error(`${response.status} ${text}`); |
80 | } |
81 | return await response.json(); |
82 | } |
83 |
|