Work with Attachments
With HAPI and the native fetch API, you can add, inspect, and read attachments on work items. This page walks you through working with attachments using Issues.getByKey and direct REST calls via fetch.
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 one or more files to a work item, including the requiredX-Atlassian-Token: no-checkheader. - Get attachment metadata from an issue: Demonstrates how to call
Issues.getByKeyand returnissue.fields.attachment, which contains metadata (such as filename, 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 via
Issues.getByKey. - Use
fetchwith theGETmethod and each attachmentidto download attachment content. - Check
mimeTypeto detect text files and decodeArrayBuffercontent withTextDecoder, or handle binary content directly.
- Fetch a work item and its attachments via