0
Upload an image
One script reply has been approved by the moderators Verified

Upload an image with up to 10 Megabytes using a single HTTP POST (multipart/form-data) request. An image can be uploaded by sending an image file or passing an accessible to an API url.

Created by hugo697 151 days ago Viewed 3721 times
0
Submitted by hugo697 Typescript (fetch-only)
Verified 151 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Upload an image
8
 * Upload an image with up to 10 Megabytes using a single HTTP POST (multipart/form-data) request.
9
An image can be uploaded by sending an image file or passing an accessible to an API url.
10

11
 */
12
export async function main(
13
  auth: Cloudflare,
14
  account_identifier: string,
15
  body: {
16
    metadata?: { [k: string]: unknown };
17
    requireSignedURLs?: boolean;
18
    [k: string]: unknown;
19
  } & (
20
    | { file: { [k: string]: unknown }; [k: string]: unknown }
21
    | { url: string; [k: string]: unknown }
22
  )
23
) {
24
  const url = new URL(
25
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/images/v1`
26
  );
27

28
  const formData = new FormData();
29
  for (const [k, v] of Object.entries(body)) {
30
    if (v !== undefined && v !== "") {
31
      formData.append(k, String(v));
32
    }
33
  }
34
  const response = await fetch(url, {
35
    method: "POST",
36
    headers: {
37
      "X-AUTH-EMAIL": auth.email,
38
      "X-AUTH-KEY": auth.key,
39
      Authorization: "Bearer " + auth.token,
40
    },
41
    body: formData,
42
  });
43
  if (!response.ok) {
44
    const text = await response.text();
45
    throw new Error(`${response.status} ${text}`);
46
  }
47
  return await response.json();
48
}
49