How to handle Jira issue attachments with Javascript code

System administration

Software development and DevOps

how to handle issue attachments in jira from javascript code
Dan Tombs

Dan Tombs

Oct 16, 2021

Recently, I've used my 20% time allocation to make a new Jira plugin available from the Atlassian Marketplace Image Annotator for Jira. The idea behind this project was to create an image editor for image attachments, seamlessly integrated with Jira. One of the challenges I encountered was handling attachments directly from frontend code (this plugin is 99% made in JavaScript).

After finding out the correct REST path to make the AJAX calls (/rest/api/2/issue/ISSUE_ID/attachments), the question was, what should be set as a data argument? Jira requires the request to be multipart, so if you want to use jQuery's ajax method, then you have to use the FormData object:

File form data

But it turned out that it was not enough. Jira complained about the image name not being sent with the request. Quick research revealed that FormData.append() method has two versions. The third argument can be added, and this third argument is the file name. Exactly what I was looking for! Please be advised that some IDEs, like IntelliJ IDEA, say that FormData.append() takes only two arguments, not three. Yet, I tested this method in 4 different browsers (Chrome, Firefox, Safari, and IE11), and in all of them, adding a third argument worked fine. So, finally, FormData.append() looked like that:

Formdata append filename

You may wonder what this blob is. The blob type is just a representation of our file that is going to be attached to an issue. This is raw data; in every case, this object should be created differently. In the most simple case, plain text file, the code is following:

Formdata blob

Finally, having all the data we need, we can make the ajax call:

Formdata ajax call

I hope you will find this article useful, and it took me quite a while to find out how to create a proper data object and save it as an issue attachment, all done in JavaScript code.

Last but not least, I encourage you to try our brand new plugin, Image Annotator, for Jira. If you like it, you can vote for it on Codegeist Hackathon (only a few days left!). Every vote counts. 

Dan Tombs

Dan Tombs

Dan Tombs is a Solution Architect at Appfire with hands-on experience across the Atlassian ecosystem since 2016. He’s worked with end customers, solution partners, and now helps teams thrive by shaping tools and processes around how they actually work and not the other way around. Dan champions automation as a path to scaling productivity, reducing context switching, and unlocking what teams do best.