0

Upload Image From File

by
Published Apr 8, 2025

Upload an image from a file. If you want to import an image from an existing url or a data uri, use the Upload Image From URL endpoint instead.*Rate limits*:Burst: `3/s`Steady: `100/m`Daily: `100/d` **Scopes:** `images:write`

Script klaviyo Verified

The script

Submitted by hugo697 Bun
Verified 428 days ago
1
//native
2
type Klaviyo = {
3
  apiKey: string;
4
};
5
type Base64 = string;
6
/**
7
 * Upload Image From File
8
 * Upload an image from a file.
9

10
If you want to import an image from an existing url or a data uri, use the Upload Image From URL endpoint instead.*Rate limits*:Burst: `3/s`Steady: `100/m`Daily: `100/d`
11

12
 */
13
export async function main(
14
  auth: Klaviyo,
15
  revision: string,
16
  body: {
17
    file: {
18
      base64: Base64;
19
      type:
20
        | "image/png"
21
        | "image/jpeg"
22
        | "image/gif"
23
        | "application/pdf"
24
        | "appication/json"
25
        | "text/csv"
26
        | "text/plain"
27
        | "audio/mpeg"
28
        | "audio/wav"
29
        | "video/mp4";
30
      name: string;
31
    };
32
    name?: string;
33
    hidden?: false | true;
34
  },
35
) {
36
  const url = new URL(`https://a.klaviyo.com/api/image-upload`);
37

38
  const formData = new FormData();
39
  for (const [k, v] of Object.entries(body)) {
40
    if (v !== undefined && v !== "") {
41
      if (["file"].includes(k)) {
42
        const { base64, type, name } = v as {
43
          base64: Base64;
44
          type: string;
45
          name: string;
46
        };
47
        formData.append(
48
          k,
49
          new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
50
            type,
51
          }),
52
          name,
53
        );
54
      } else {
55
        formData.append(k, String(v));
56
      }
57
    }
58
  }
59
  const response = await fetch(url, {
60
    method: "POST",
61
    headers: {
62
      revision: revision,
63
      "Accept": "application/vnd.api+json",
64
      Authorization: "Klaviyo-API-Key " + auth.apiKey,
65
    },
66
    body: formData,
67
  });
68
  if (!response.ok) {
69
    const text = await response.text();
70
    throw new Error(`${response.status} ${text}`);
71
  }
72
  return await response.json();
73
}
74