Work with Attachments
Learn how to add attachments to work items with fetch, get attachment metadata with Issues.getByKey, and read text or binary attachment content.
HAPI returns attachment metadata, but adding attachments and reading their content use direct REST calls through the native fetch API. You can find in-app example scripts for each of these tasks.
Pattern for working with attachments with HAPI
When you work with attachments, you typically:
- Import
Issuesfrom@scriptrunnerhq/hapi/issuesto fetch issues and their attachment metadata. - Use
fetchwithFormDataandBlobto upload files to a work item via the Jira REST API. - Use
Issues.getByKeyto accessissue.fields.attachment. - Use
fetchto retrieve attachment content by attachment ID.
The following example shows this general pattern:
import * as Issues from '@scriptrunnerhq/hapi/issues'
export default async function () {
// 1. Add an attachment to a work item
const form = new FormData()
form.append('file', new Blob(['file contents here'], { type: 'text/plain' }), 'example.txt')
const uploadResponse = await fetch('/rest/api/3/issue/WORKITEM_KEY/attachments', {
method: 'POST',
headers: {
'X-Atlassian-Token': 'no-check',
},
body: form,
})
if (!uploadResponse.ok) {
throw new Error(`Failed to add attachment: ${uploadResponse.status}`)
}
// 2. Fetch the work item and read attachment metadata
const issue = await Issues.getByKey('WORKITEM_KEY')
if (!issue) {
throw new Error('Issue not found')
}
const attachments = issue.fields.attachment
// 3. Optionally, fetch and process attachment content
// if (attachments) {
// for (const a of attachments) {
// const response = await fetch(`/rest/api/3/attachment/content/${a.id}`, {
// headers: { Accept: '*/*' },
// })
// const content = await response.arrayBuffer()
// // Decode or handle the content here (e.g. text vs binary)
// }
// }
}In‑app example scripts build on this pattern to cover specific use cases, such as adding attachments, reading attachment metadata, and downloading/decoding attachment content.
In-app example scripts
The following examples are available in-app:
- Add an Attachment to a Work Item: Shows how to use
fetchwithFormDataandBlobto attach a file to a work item, including the requiredX-Atlassian-Token: no-checkheader. - Get Attachment Metadata from an Issue: Shows how to call
Issues.getByKeyand returnissue.fields.attachment, which contains metadata (such as file name, size, MIME type, and ID) for all attachments on the work item. - Read Attachment Content from an Issue: Shows how to:
- Fetch a work item and its attachments using
Issues.getByKey. - Use
fetchwith theGETmethod and each attachment'sidto read attachment content. - Check
mimeTypeto detect text files and decodeArrayBuffercontent withTextDecoder, or handle binary content directly.
- Fetch a work item and its attachments using