Download and display Jira issue attachments with Forge

@JulianWolf

I had a similar issue, but instead of fetching attachments, I was trying to fetch issueType icon images when the user setup a custom image. I worked out a “hacky” solution that works for my case, so I believe it might work in your case as well:

Based on another post, Requesting binary data with requestJira when using the Forge Bridge, I learned that forge functions in the “backend” are able to fetch the binary contents without “corrupting” it. In fact, forge/@bridge corrupts the image because it interprets the binary response as text (related issue) .

With that knowledge, I wrote the following forge function (not frontend, this a “backend” function, defined in a forge module).

import api, {route} from "@forge/api";
const resolver = new Resolver();
resolver.define('requestJiraAsDataUrl', async(req) => {
    let restApi = req.payload.restApi
    let response =  await api.asUser().requestJira(route `${restApi}`, {})
    let contentType = response.headers.get('content-type')
    const arrayBuffer = await response.arrayBuffer();
    const base64 = Buffer.from(arrayBuffer).toString('base64')
    return `data:${contentType};base64,${base64}`
})

This function can be invoked from the CustomUI using @forge/bridge invoke function, like this:

let dataUrl:string = await invoke("requestJiraAsDataUrl", {restApi: "/rest/api/3/attachment/content/" + attachmentId})

This invocation will return the dataUrl for the given attachment. That will be something like this:

data:image/png;charset=UTF-8;base64,iVBORw0KGgoAAAANSUhEUgAAADA...

This works because await api.asUser().requestJira has the required credentials in the request to fetch image.

Finally, all you have to do is set y our img.src with the returned value and, hopefully, that will work

Cheers

1 Like