The Adaptavist Group LogoDocumentation

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 Issues from @scriptrunnerhq/hapi/issues to fetch issues and their attachment metadata.
  • Use fetch with FormData and Blob to upload files to a work item via the Jira REST API.
  • Use Issues.getByKey to access issue.fields.attachment.
  • Use fetch to 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 fetch with FormData and Blob to attach one or more files to a work item, including the required X-Atlassian-Token: no-check header.
  • Get attachment metadata from an issue: Demonstrates how to call Issues.getByKey and return issue.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 fetch with the GET method and each attachment id to download attachment content.
    • Check mimeType to detect text files and decode ArrayBuffer content with TextDecoder, or handle binary content directly.

Search documentation

Start typing to search the docs.