0

Update attachment data

by
Published Oct 17, 2025

Updates the binary data of an attachment, given the attachment ID, and optionally the comment and the minor edit field.

Script confluence Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Confluence = {
3
	email: string
4
	apiToken: string
5
	domain: string
6
}
7
type Base64 = string
8
/**
9
 * Update attachment data
10
 * Updates the binary data of an attachment, given the attachment ID, and
11
optionally the comment and the minor edit field.
12
 */
13
export async function main(
14
	auth: Confluence,
15
	id: string,
16
	attachmentId: string,
17
	body: {
18
		file: {
19
			base64: Base64
20
			type:
21
				| 'image/png'
22
				| 'image/jpeg'
23
				| 'image/gif'
24
				| 'application/pdf'
25
				| 'appication/json'
26
				| 'text/csv'
27
				| 'text/plain'
28
				| 'audio/mpeg'
29
				| 'audio/wav'
30
				| 'video/mp4'
31
			name: string
32
		}
33
		comment?: {
34
			base64: Base64
35
			type:
36
				| 'image/png'
37
				| 'image/jpeg'
38
				| 'image/gif'
39
				| 'application/pdf'
40
				| 'appication/json'
41
				| 'text/csv'
42
				| 'text/plain'
43
				| 'audio/mpeg'
44
				| 'audio/wav'
45
				| 'video/mp4'
46
			name: string
47
		}
48
		minorEdit: {
49
			base64: Base64
50
			type:
51
				| 'image/png'
52
				| 'image/jpeg'
53
				| 'image/gif'
54
				| 'application/pdf'
55
				| 'appication/json'
56
				| 'text/csv'
57
				| 'text/plain'
58
				| 'audio/mpeg'
59
				| 'audio/wav'
60
				| 'video/mp4'
61
			name: string
62
		}
63
	}
64
) {
65
	const url = new URL(
66
		`https://${auth.domain}/wiki/rest/api/content/${id}/child/attachment/${attachmentId}/data`
67
	)
68

69
	const formData = new FormData()
70
	for (const [k, v] of Object.entries(body)) {
71
		if (v !== undefined) {
72
			if (['file', 'comment', 'minorEdit'].includes(k)) {
73
				const { base64, type, name } = v as {
74
					base64: Base64
75
					type: string
76
					name: string
77
				}
78
				formData.append(
79
					k,
80
					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
81
						type
82
					}),
83
					name
84
				)
85
			} else {
86
				formData.append(k, String(v))
87
			}
88
		}
89
	}
90
	const response = await fetch(url, {
91
		method: 'POST',
92
		headers: {
93
			Authorization: 'Basic ' + btoa(`${auth.email}:${auth.apiToken}`)
94
		},
95
		body: formData
96
	})
97
	if (!response.ok) {
98
		const text = await response.text()
99
		throw new Error(`${response.status} ${text}`)
100
	}
101
	return await response.json()
102
}
103