
Uploading Attachments to Jira Service Management Cloud Assets Without Public API Documentation
The Three-Step Process Overview
Attachment uploads to Jira Assets require three separate API calls. You cannot simply POST a file to an object. The process works as follows:
- Get upload credentials from the Assets API
- Upload the file to Atlassian's media service using those credentials
- Link the uploaded file to the specific Assets object
This three-step approach exists because the media service and Assets service are separate systems. The media service handles the file storage, while the Assets service manages the metadata and associations.
Step 1: Getting Upload Credentials
The first step is to request upload credentials for a specific Assets object. This tells the system you intend to upload something and provides you with temporary access tokens.
1async getUploadCredentials(objectId) {
2 const url = `https://api.atlassian.com/jsm/assets/workspace/${this.workspaceId}/v1/attachments/object/${objectId}/credentials`;
3
4 return new Promise((resolve, reject) => {
5 const options = {
6 method: "GET",
7 headers: {
8 Authorization: `Basic ${this.apiToken}`,
9 Accept: "application/json",
10 "Content-Type": "application/json",
11 },
12 };
13
14 const req = https.request(url, options, (res) => {
15 let data = "";
16
17 res.on("data", (chunk) => {
18 data += chunk;
19 });
20
21 res.on("end", () => {
22 if (res.statusCode === 200) {
23 try {
24 const credentials = JSON.parse(data);
25 resolve(credentials);
26 } catch (error) {
27 reject(
28 new Error(
29 `Failed to parse credentials response: ${error.message}`,
30 ),
31 );
32 }
33 } else {
34 reject(
35 new Error(
36 `Failed to get upload credentials: HTTP ${res.statusCode} - ${data}`,
37 ),
38 );
39 }
40 });
41 });
42
43 req.on("error", (error) => {
44 reject(new Error(`Request failed: ${error.message}`));
45 });
46
47 req.end();
48 });
49}
50The response from this endpoint provides three critical pieces of information:
clientId: An identifier for the client making the uploadmediaBaseUrl: The base URL for the media service where files are storedmediaJwtToken: A JWT token for authenticating with the media service
This endpoint uses Basic authentication (your email and API token), not the JWT token. The JWT token is only used when uploading to the media service in step 2.
Step 2: Uploading to Media Service
Once you have credentials, you upload the actual file to Atlassian's media service. This service handles file storage separately from Assets.
1async uploadFileToMediaService(filePath, filename, credentials) {
2 const { clientId, mediaBaseUrl, mediaJwtToken } = credentials;
3
4 return new Promise((resolve, reject) => {
5 // Check if file exists and get its stats
6 if (!fs.existsSync(filePath)) {
7 reject(new Error(`File not found: ${filePath}`));
8 return;
9 }
10
11 const fileStats = fs.statSync(filePath);
12
13 // Check file size
14 if (fileStats.size > this.config.maxFileSize) {
15 reject(
16 new Error(
17 `File too large: ${fileStats.size} bytes (max: ${this.config.maxFileSize} bytes)`,
18 ),
19 );
20 return;
21 }
22
23 const encodedFilename = encodeURIComponent(filename);
24 // Fixed endpoint: Atlassian changed from /file/binary to /file
25 const uploadUrl = `${mediaBaseUrl}/file?name=${encodedFilename}`;
26
27 const form = new FormData();
28 form.append("file", fs.createReadStream(filePath));
29
30 const options = {
31 method: "POST",
32 headers: {
33 "X-Client-Id": clientId,
34 Authorization: `Bearer ${mediaJwtToken}`,
35 ...form.getHeaders(),
36 },
37 };
38
39 const parsedUrl = new URL(uploadUrl);
40 const isHttps = parsedUrl.protocol === "https:";
41 const requestModule = isHttps ? https : http;
42
43 const req = requestModule.request(uploadUrl, options, (res) => {
44 let data = "";
45
46 res.on("data", (chunk) => {
47 data += chunk;
48 });
49
50 res.on("end", () => {
51 if (res.statusCode === 200 || res.statusCode === 201) {
52 try {
53 const response = JSON.parse(data);
54 resolve({
55 mediaId: response.data?.id || response.id,
56 mediaSize: response.data?.size || response.size || fileStats.size,
57 });
58 } catch (error) {
59 reject(
60 new Error(`Failed to parse upload response: ${error.message}`),
61 );
62 }
63 } else {
64 reject(
65 new Error(
66 `Failed to upload file: HTTP ${res.statusCode} - ${data}`,
67 ),
68 );
69 }
70 });
71 });
72
73 req.on("error", (error) => {
74 reject(new Error(`Upload request failed: ${error.message}`));
75 });
76
77 form.pipe(req);
78 });
79}
80Key aspects of this step:
- Uses the JWT token for authentication, not Basic auth
- Uploads as
multipart/form-datawith a field namedfile - Returns a
mediaIdthat identifies the uploaded file - The endpoint is
{mediaBaseUrl}/file?name={encodedFilename}- note the change from/file/binaryto/file
The response contains the mediaId which is the reference you'll need in the final step.
Step 3: Linking to Asset Object
The final step is to tell Assets that a specific file should be associated with a specific object. This creates the relationship between the uploaded file and the Assets object.
1async linkAttachmentToObject(objectId, attachmentData) {
2 const url = `https://api.atlassian.com/jsm/assets/workspace/${this.workspaceId}/v1/attachments/object/${objectId}`;
3
4 const payload = {
5 attachments: [attachmentData],
6 };
7
8 return new Promise((resolve, reject) => {
9 const postData = JSON.stringify(payload);
10
11 const options = {
12 method: "POST",
13 headers: {
14 Authorization: `Basic ${this.apiToken}`,
15 Accept: "application/json",
16 "Content-Type": "application/json",
17 "Content-Length": Buffer.byteLength(postData),
18 },
19 };
20
21 const req = https.request(url, options, (res) => {
22 let data = "";
23
24 res.on("data", (chunk) => {
25 data += chunk;
26 });
27
28 res.on("end", () => {
29 if (res.statusCode === 200 || res.statusCode === 201) {
30 try {
31 const response = JSON.parse(data);
32 resolve(response);
33 } catch (error) {
34 reject(
35 new Error(`Failed to parse link response: ${error.message}`),
36 );
37 }
38 } else {
39 reject(
40 new Error(
41 `Failed to link attachment: HTTP ${res.statusCode} - ${data}`,
42 ),
43 );
44 }
45 });
46 });
47
48 req.on("error", (error) => {
49 reject(new Error(`Link request failed: ${error.message}`));
50 });
51
52 req.write(postData);
53 req.end();
54 });
55}
56The attachmentData object must include:
1const attachmentData = {
2 contentType: "application/pdf", // MIME type of the file
3 filename: "document.pdf", // Original filename
4 mediaId: "abc123xyz", // The mediaId returned from step 2
5 size: 1234567, // File size in bytes
6 comment: "Optional comment" // Optional attachment comment
7};
8This endpoint also uses Basic authentication. The response confirms the attachment has been linked successfully.
Putting It All Together
Here's how the complete upload process works for a single attachment:
1async uploadSingleAttachment(objectId, attachmentMetadata, filePath) {
2 const { filename, comment = "" } = attachmentMetadata;
3
4 try {
5 console.log(`๐ Uploading: ${filename}`);
6
7 // Step 1: Get upload credentials
8 const credentials = await this.getUploadCredentials(objectId);
9 console.log(` โ Got upload credentials`);
10
11 // Step 2: Upload file to media service
12 const uploadResult = await this.uploadFileToMediaService(
13 filePath,
14 filename,
15 credentials,
16 );
17 console.log(` โ Uploaded to media service (ID: ${uploadResult.mediaId})`);
18
19 // Step 3: Link attachment to object
20 const attachmentData = {
21 contentType: getMimeType(filename),
22 filename: filename,
23 mediaId: uploadResult.mediaId,
24 size: uploadResult.mediaSize,
25 comment: comment,
26 };
27
28 const linkResult = await this.linkAttachmentToObject(
29 objectId,
30 attachmentData,
31 );
32 console.log(` โ
Successfully linked attachment to object`);
33
34 return { success: true, result: linkResult };
35 } catch (error) {
36 console.error(` โ Failed to upload ${filename}: ${error.message}`);
37 return { success: false, error: error.message };
38 }
39}
40Important Considerations
No Timeouts for File Uploads
File uploads can take significant time, especially for large files or slow connections. The implementation uses zero timeouts:
1const options = {
2 method: "POST",
3 headers: { ... },
4 // NO TIMEOUT - file uploads must complete naturally regardless of size
5};
6Do not impose timeouts on the file upload request. Let it complete naturally. If it fails, handle the error rather than timing out.
MIME Type Detection
Proper MIME type detection is important for the link step:
1function getMimeType(filename) {
2 const ext = path.extname(filename).toLowerCase();
3 const mimeTypes = {
4 ".pdf": "application/pdf",
5 ".jpg": "image/jpeg",
6 ".jpeg": "image/jpeg",
7 ".png": "image/png",
8 ".gif": "image/gif",
9 ".doc": "application/msword",
10 ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
11 ".xls": "application/vnd.ms-excel",
12 ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
13 ".txt": "text/plain",
14 ".zip": "application/zip",
15 ".7z": "application/x-7z-compressed",
16 ".tar": "application/x-tar",
17 ".gz": "application/gzip",
18 };
19
20 return mimeTypes[ext] || "application/octet-stream";
21}
22Error Handling
Each step can fail independently. Handle errors at each step rather than trying a single try-catch for the entire process:
1try {
2 const credentials = await this.getUploadCredentials(objectId);
3} catch (error) {
4 // Handle credentials failure specifically
5 console.error('Failed to get credentials:', error.message);
6 return;
7}
8
9try {
10 const uploadResult = await this.uploadFileToMediaService(filePath, filename, credentials);
11} catch (error) {
12 // Handle upload failure specifically
13 console.error('Failed to upload file:', error.message);
14 return;
15}
16
17try {
18 const linkResult = await this.linkAttachmentToObject(objectId, attachmentData);
19} catch (error) {
20 // Handle link failure specifically
21 console.error('Failed to link attachment:', error.message);
22 return;
23}
24This way, you can provide better error messages and potentially retry only the step that failed.
Authentication Differences
Remember the authentication pattern:
- Step 1 (Get credentials): Basic auth (email + API token)
- Step 2 (Upload file): JWT token (from step 1 response)
- Step 3 (Link attachment): Basic auth (email + API token)
Mixing these up will cause failures.
File Size Limits
Check file sizes before uploading to avoid wasting bandwidth on files that will be rejected:
1const fileStats = fs.statSync(filePath);
2const maxFileSize = 100 * 1024 * 1024; // 100 MB
3
4if (fileStats.size > maxFileSize) {
5 throw new Error(`File too large: ${fileStats.size} bytes (max: ${maxFileSize} bytes)`);
6}
7Conclusion
The three-step attachment upload process for Jira Assets is not documented publicly but is straightforward once you understand it. The key insights are:
- You must request credentials for each object
- Files go to a separate media service
- Linking is a separate API call after upload
- Authentication varies between steps
- Do not timeout file uploads
This pattern ensures separation of concerns between storage (media service) and metadata (Assets service), which is a common pattern in cloud architectures.

Comments
0Add a comment