Create authenticated direct upload URL V2

Direct uploads allow users to upload images without API keys. A common use case are web apps, client-side applications, or mobile devices where users upload content directly to Cloudflare Images. This method creates a draft record for a future image. It returns an upload URL and an image identifier. To verify if the image itself has been uploaded, send an image details request (accounts/:account_identifier/images/v1/:identifier), and check that the `draft: true` property is not present.

Script cloudflare Verified

by hugo697 ยท 11/16/2023

The script

Submitted by hugo697 Typescript (fetch-only)
Verified 383 days ago
1
type Cloudflare = {
2
  token: string;
3
  email: string;
4
  key: string;
5
};
6
/**
7
 * Create authenticated direct upload URL V2
8
 * Direct uploads allow users to upload images without API keys. A common use case are web apps, client-side applications, or mobile devices where users upload content directly to Cloudflare Images. This method creates a draft record for a future image. It returns an upload URL and an image identifier. To verify if the image itself has been uploaded, send an image details request (accounts/:account_identifier/images/v1/:identifier), and check that the `draft: true` property is not present.
9
 */
10
export async function main(
11
  auth: Cloudflare,
12
  account_identifier: string,
13
  body: {
14
    expiry?: string;
15
    id?: string;
16
    metadata?: { [k: string]: unknown };
17
    requireSignedURLs?: boolean;
18
    [k: string]: unknown;
19
  }
20
) {
21
  const url = new URL(
22
    `https://api.cloudflare.com/client/v4/accounts/${account_identifier}/images/v2/direct_upload`
23
  );
24

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