Search code examples
javaunirestjira-rest-java-api

Unable to attach file to issue in jira via rest api Java


I want to attach multiple files to issue. I'm able to create issue successfully however i am facing problem in attaching documents after creating issue. I have referred to this link SOLVED: attach a file using REST from scriptrunner I am getting 404 error even though issue exists and also user has all the permissions.

File fileToUpload = new File("D:\\dummy.txt");
InputStream in = null;
try {
    in = new FileInputStream(fileToUpload);
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

HttpResponse < String > response3 = Unirest
    .post("https://.../rest/api/2/issue/test-85/attachments")
    .basicAuth(username, password).field("file", in , "dummy.txt")
    .asString();
System.out.println(response3.getStatus());

here test-85 is a issueKey value. And i am using open-unirest-java-3.3.06.jar. Is the way i am attaching documents is correct?


Solution

  • I am not sure how open-unirest manages its fields, maybe it tries to put them as json field, rather than post content.

    I've been using Rcarz's Jira client. It's a little bit outdated but it still works. Maybe looking at its code will help you, or you can just use it directly. The Issue class:

    public JSON addAttachment(File file) throws JiraException {
        try {
            return restclient.post(getRestUri(key) + "/attachments", file);
        } catch (Exception ex) {
            throw new JiraException("Failed add attachment to issue " + key, ex);
        }
    }
    

    And in RestClient class:

    import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
    import org.apache.http.entity.mime.MultipartEntity;
    import org.apache.http.entity.mime.content.FileBody;
    
    public JSON post(String path, File file) throws RestException, IOException, URISyntaxException {
        return request(new HttpPost(buildURI(path)), file);
    }
    
    private JSON request(HttpEntityEnclosingRequestBase req, File file) throws RestException, IOException {
        if (file != null) {
            File fileUpload = file;
            req.setHeader("X-Atlassian-Token", "nocheck");
            MultipartEntity ent = new MultipartEntity();
            ent.addPart("file", new FileBody(fileUpload));
            req.setEntity(ent);
        }
        return request(req);
    }
    

    So I'm not sure why you're getting a 404, Jira is sometime fuzzy and not really clear about its error, try printing the full error, or checking Jira's log if you can. Maybe it's just the "X-Atlassian-Token", "nocheck", try adding it.