0

Create File From Text

by
Published today

Create a Google Drive file (or Google Doc) from a text string.

Script gdrive Verified

The script

Submitted by hugo989 Typescript (fetch-only)
Verified 48 minutes ago
1
//native
2

3
/**
4
 * Create File From Text
5
 * Create a file from a string. Leave `mime_type` as text/plain for a .txt file, or set `convert_to_google_doc` to create an editable Google Doc from the text.
6
 */
7
export async function main(
8
  auth: RT.Gdrive,
9
  name: string,
10
  content: string,
11
  folder_id: string | undefined,
12
  mime_type: string = "text/plain",
13
  convert_to_google_doc: boolean = false
14
) {
15
  const metadata: { [key: string]: any } = { name }
16
  if (folder_id !== undefined && folder_id !== "")
17
    metadata.parents = [folder_id]
18
  if (convert_to_google_doc)
19
    metadata.mimeType = "application/vnd.google-apps.document"
20

21
  // multipart/related: JSON metadata part, then the content part.
22
  const boundary = crypto.randomUUID()
23
  const body = [
24
    `--${boundary}`,
25
    "Content-Type: application/json; charset=UTF-8",
26
    "",
27
    JSON.stringify(metadata),
28
    `--${boundary}`,
29
    `Content-Type: ${mime_type}; charset=UTF-8`,
30
    "",
31
    content,
32
    `--${boundary}--`,
33
  ].join("\r\n")
34

35
  const url = new URL("https://www.googleapis.com/upload/drive/v3/files")
36
  url.searchParams.append("uploadType", "multipart")
37
  url.searchParams.append("supportsAllDrives", "true")
38

39
  const response = await fetch(url, {
40
    method: "POST",
41
    headers: {
42
      Authorization: `Bearer ${auth.token}`,
43
      "Content-Type": `multipart/related; boundary=${boundary}`,
44
      Accept: "application/json",
45
    },
46
    body,
47
  })
48

49
  if (!response.ok) {
50
    throw new Error(`${response.status} ${await response.text()}`)
51
  }
52

53
  return await response.json()
54
}
55