It's all about the answers!

Ask a question

How to add attachment to workitem by JAVA API?


Jia Jia Li (8058157192) | asked May 19 '15, 6:06 a.m.
I have not investigated much on this requirement, but firstly post the question to see if any one has the experience.
Thanks for your help.
I guess it maybe the work item link?

Thanks!

One answer



permanent link
Ralph Schoon (63.3k33646) | answered May 19 '15, 6:34 a.m.
FORUM ADMINISTRATOR / FORUM MODERATOR / JAZZ DEVELOPER
See below. getWorkingCopy() returns the workingcopy for the work item that the attachment goes to.
	/**
	 * Utility method to upload and attach a file to a work item
	 * 
	 * @param fileName
	 *            - the file name of the file to upload
	 * @param description
	 *            - the description of the attachment
	 * @param contentType
	 *            - the content type of the file
	 * @param encoding
	 *            - the encoding of the file
	 * 
	 * @throws TeamRepositoryException
	 */
	private void attachFile(String fileName, String description,
			String contentType, String encoding) throws TeamRepositoryException {

		File attachmentFile = new File(fileName);
		FileInputStream fis;
		try {
			fis = new FileInputStream(attachmentFile);
			try {
				IAttachment newAttachment = getWorkItemClient()
						.createAttachment(getWorkItem().getProjectArea(),
								attachmentFile.getName(), description,
								contentType, encoding, fis, monitor);

				newAttachment = (IAttachment) newAttachment.getWorkingCopy();
				newAttachment = getWorkItemCommon().saveAttachment(
						newAttachment, monitor);
				IItemReference reference = WorkItemLinkTypes
						.createAttachmentReference(newAttachment);

				getWorkingCopy().getReferences().add(
						WorkItemEndPoints.ATTACHMENT, reference);

			} finally {
				if (fis != null) {
					fis.close();
				}
			}
		} catch (FileNotFoundException e) {
			throw new WorkItemCommandLineException(
					"Attach File - File not found: " + fileName, e);
		} catch (IOException e) {
			throw new WorkItemCommandLineException(
					"Attach File - I/O Exception: " + fileName, e);
		}
	}

Comments
Ralph Schoon commented May 19 '15, 6:35 a.m. | edited May 19 '15, 6:38 a.m.
FORUM ADMINISTRATOR / FORUM MODERATOR / JAZZ DEVELOPER

You could save all that time if you could look at my blog, all that is already explained there.


Ralph Schoon commented May 19 '15, 6:38 a.m.
FORUM ADMINISTRATOR / FORUM MODERATOR / JAZZ DEVELOPER

ContentType has one of the following values:

  • text/plain
  • application/unknown
  • application/xml

Encodinghas one of the following values:

  • UTF-8
  • UTF-16LE
  • UTF-16BE
  • us-ascii.

Your answer


Register or to post your answer.


Dashboards and work items are no longer publicly available, so some links may be invalid. We now provide similar information through other means. Learn more here.