Create
cancel
Showing results for 
Search instead for 
Did you mean: 
Sign up Log in
Celebration

Earn badges and make progress

You're on your way to the next level! Join the Kudos program to earn points and save your progress.

Deleted user Avatar
Deleted user

Level 1: Seed

25 / 150 points

Next: Root

Avatar

1 badge earned

Collect

Participate in fun challenges

Challenges come and go, but your rewards stay with you. Do more to earn more!

Challenges
Coins

Gift kudos to your peers

What goes around comes around! Share the love by gifting kudos to your peers.

Recognition
Ribbon

Rise up in the ranks

Keep earning points to reach the top of the leaderboard. It resets every quarter so you always have a chance!

Leaderboard

Come for the products,
stay for the community

The Atlassian Community can help you and your team get more value out of Atlassian products and practices.

Atlassian Community about banner
4,553,382
Community Members
 
Community Events
184
Community Groups

SOLVED: attach a file using REST from scriptrunner

Edited
Derek Fields
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 13, 2019

I have created a very simple test script to figure out how to attach a file to an issue. The "file" is actually just text that I want to create a file. Since this is in the Cloud, I am assuming that I can't write the file to a temp file in order to import it.

import org.apache.http.entity.ContentType;
String text = "This is a simple set of text"


def response = Unirest.post("/rest/api/3/issue/CDFT-1/attachments")
.header("Accept", "application/json")
.header("Content-Type", "text/plain")
.header("X-Atlassian-Token", "no-check")
.field("file", text.getBytes(), "text.txt")
.asJson();

I get a 415 - Unsupported Media Type error from this. Any help is welcome

2 answers

1 accepted

5 votes
Answer accepted
Derek Fields
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 18, 2019

After a lot of experimentation, I was able to successfully attach the file with the following code:

 

String key = 'MP-59'
def newBody = "Here is a text file that I want to attach"

InputStream stream = new ByteArrayInputStream(newBody.getBytes())

def resp = Unirest.post("/rest/api/3/issue/${key}/attachments")
.header("X-Atlassian-Token", "no-check")
.field('file', stream, 'test.txt')
.asJson()

 

The trick was to convert it to a stream so that it could be uploaded by Unirest 

Hi Derek,

thanks for the solution, it helped a lot. Unfortunately I have an issue with special characters in Czech language. For example "Č". So that, if I want to write a file with filename "Český jazyk.png", the output filename will be "?esk? jazyk.png". Can you please help me with this issue? I tried to resolve it by myself, but it was unsuccesfull.

Many thanks.

Best regards,

Lukas

1 vote
Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
Jun 17, 2019

I've never user Unirest ...  or jira-cloud ... but had some issues like that with an actual file and I ended up with something like this using httpBuilder:

def file = new File(filePath)
def
fileEntity = new MultipartEntityBuilder()
fileEntity.addBinaryBody("file", file)

def httpBuilder = new HTTPBuilder(baseUrl)
httpBuilder.request(Method.POST, "/rest/api/latest/issue/$key/attachments"){req ->
headers.Authorization = "myBasicAuthString"
body = fileEntity.build()
}
Derek Fields
Rising Star
Rising Star
Rising Stars are recognized for providing high-quality answers to other users. Rising Stars receive a certificate of achievement and are on the path to becoming Community Leaders.
Jun 18, 2019

Note that I am not attaching an existing file, but a "file" that is simply a text string. Because I am in the Cloud, I can't create the file on disk first and then read it in as a file.

Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
Jun 18, 2019

I know, I just wanted to provide the example of creating the fileEntity using the multipartEntyBuilder

btw, here is the full class path: 

import org.apache.http.entity.mime.MultipartEntityBuilder

 Looking that up a little, I see that you can do the following:

import org.apache.http.entity.mime.MultipartEntityBuilder
import groovyx.net.http.*

String text = "This is a simple set of text"

def
fileEntity = new MultipartEntityBuilder()
fileEntity.asTextBody("file", text)

def httpBuilder = new HTTPBuilder(baseUrl)
httpBuilder.request(Method.POST, "/rest/api/latest/issue/$key/attachments"){req ->
headers.Authorization = "myBasicAuthString"
body = fileEntity.build()
}

I  try to do as you @Peter-Dave Sheehan  but I have

Exception : java.lang.IllegalArgumentException: No encoder found for request content type */*

here is code 

def f = new File("/u/app/jira/jira_home/data/attachments/attach1.jpeg")
fileEntity.addBinaryBody("file", f)
def http = new HTTPBuilder("${addressJira}/rest/api/2/issue/TEST-1/attachments")
http.setClient(HttpClients.custom().setDefaultRequestConfig(defaultRequestConfig).build())
try {
http.request(POST) {
headers.'Authorization' = "Basic ${authString}"
headers."X-Atlassian-Token: nocheck"
// if add ContentType.ANY nothing changes
//contentType = ContentType.ANY
body = fileEntity.build()

response.success = { resp, json ->
log.info("Resp status " + resp.status.toString())
}

response.failure = { resp ->
log.warn("response code is : " + resp.status.toString())}
}
} catch (Exception exception) {
log.warn("Exception : " + exception)
}

 

Peter-Dave Sheehan
Community Leader
Community Leader
Community Leaders are connectors, ambassadors, and mentors. On the online community, they serve as thought leaders, product experts, and moderators.
Jun 01, 2021

Have you tried with

contentType = ContentType.BINARY

 

I have no experience using HTTPBuilder.setClient() methods.

Yes, I've tried, no luck.

That works

HttpClient httpClient = HttpClientBuilder.create().build()
HttpPost httpPost = new HttpPost("${addressJira}/rest/api/latest/issue/TEST-1013/attachments")
httpPost.setHeader("Authorization", "Basic ${authString}")
httpPost.setHeader("X-Atlassian-Token", "nocheck")
MultipartEntityBuilder entity = MultipartEntityBuilder.create()
entity.addPart("file", new FileBody(file))
httpPost.setEntity(entity.build())
HttpResponse response = httpClient.execute(httpPost)
log.warn(response.statusLine)

Suggest an answer

Log in or Sign up to answer
TAGS
AUG Leaders

Atlassian Community Events