0

Upload attachment

by
Published Oct 17, 2025

Creates an attachment in the accounting software against the given transactionId

Script codat Verified

The script

Submitted by hugo697 Bun
Verified 235 days ago
1
//native
2
type Codat = {
3
	encodedKey: string
4
}
5
type Base64 = string
6
/**
7
 * Upload attachment
8
 * Creates an attachment in the accounting software against the given transactionId
9
 */
10
export async function main(
11
	auth: Codat,
12
	companyId: string,
13
	syncId: string,
14
	transactionId: string,
15
	body: {
16
		file: {
17
			base64: Base64
18
			type:
19
				| 'image/png'
20
				| 'image/jpeg'
21
				| 'image/gif'
22
				| 'application/pdf'
23
				| 'appication/json'
24
				| 'text/csv'
25
				| 'text/plain'
26
				| 'audio/mpeg'
27
				| 'audio/wav'
28
				| 'video/mp4'
29
			name: string
30
		}
31
	}
32
) {
33
	const url = new URL(
34
		`https://api.codat.io/companies/${companyId}/sync/expenses/syncs/${syncId}/transactions/${transactionId}/attachments`
35
	)
36

37
	const formData = new FormData()
38
	for (const [k, v] of Object.entries(body)) {
39
		if (v !== undefined) {
40
			if (['file'].includes(k)) {
41
				const { base64, type, name } = v as {
42
					base64: Base64
43
					type: string
44
					name: string
45
				}
46
				formData.append(
47
					k,
48
					new Blob([Uint8Array.from(atob(base64), (m) => m.codePointAt(0)!)], {
49
						type
50
					}),
51
					name
52
				)
53
			} else {
54
				formData.append(k, String(v))
55
			}
56
		}
57
	}
58

59
	const response = await fetch(url, {
60
		method: 'POST',
61
		headers: {
62
			Authorization: `Basic ${auth.encodedKey}`
63
		},
64
		body: formData
65
	})
66
	if (!response.ok) {
67
		const text = await response.text()
68
		throw new Error(`${response.status} ${text}`)
69
	}
70
	return await response.json()
71
}
72