0

Add or update user avatar

by
Published Oct 17, 2025

Adds or updates a user avatar.

Script box Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Box = {
3
  token: string;
4
};
5
type Base64 = string;
6
/**
7
 * Add or update user avatar
8
 * Adds or updates a user avatar.
9
 */
10
export async function main(
11
  auth: Box,
12
  user_id: string,
13
  body: {
14
    pic: {
15
      base64: Base64;
16
      type:
17
        | "image/png"
18
        | "image/jpeg"
19
        | "image/gif"
20
        | "application/pdf"
21
        | "appication/json"
22
        | "text/csv"
23
        | "text/plain"
24
        | "audio/mpeg"
25
        | "audio/wav"
26
        | "video/mp4";
27
      name: string;
28
    };
29
  },
30
) {
31
  const url = new URL(`https://api.box.com/2.0/users/${user_id}/avatar`);
32

33
  const formData = new FormData();
34
  for (const [k, v] of Object.entries(body)) {
35
    if (v !== undefined) {
36
      if (["pic"].includes(k)) {
37
        const { base64, type, name } = v as {
38
          base64: Base64;
39
          type: string;
40
          name: string;
41
        };
42
        formData.append(
43
          k,
44
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
45
            type,
46
          }),
47
          name,
48
        );
49
      } else {
50
        formData.append(k, String(v));
51
      }
52
    }
53
  }
54
  const response = await fetch(url, {
55
    method: "POST",
56
    headers: {
57
      Authorization: "Bearer " + auth.token,
58
    },
59
    body: formData,
60
  });
61
  if (!response.ok) {
62
    const text = await response.text();
63
    throw new Error(`${response.status} ${text}`);
64
  }
65
  return await response.json();
66
}
67