How to copy a single attachment?

peterraeves
Mega Guru

I'm trying to copy a single attachment. Why is my code not working?

//Create copy of attachment

var gsa = new GlideSysAttachment();

var fileName = attachment.getValue('file_name');

var contentType = attachment.getValue('content_type');

var content = gsa.getContentBase64(attachment);

gsa.write(toGR, fileName, contentType, content);

I tried using 'gsa.getContent(attachment)' for line 5 as well, but that did not work either. The result was always that an attachment was created to the correct record, with the correct name, but without any content. Am I not getting the content correctly?

Kind regards,

6 REPLIES 6

This.   Yes, I know the sys_id of the one attachment I want to copy.



Scenario:   RecordA has 2 attachments.   Knowing the attachment sys_id's, I only want to copy the one attachment to RecordB


Kshitij Tripath
Tera Contributor

Hi Peter,

We can copy specific attachments from source to target table by using below code snippet. For the sake of simplicity, we are assuming that there is a field on source which stores the attachments to be copied to target table.

void function (source) {
	
	try {
		var incRef, probRef, sysAttRef;
		probRef = new GlideRecord("problem");
		incRef = new GlideRecord("incident");
		if (probRef.get(problem_guid)) {
			if (incRef.get(incident_guid)) {
				// copying specific attachments based on field [ type = glidelist ]
				sysAttRef = new GlideRecord("sys_attachment");
				sysAttRef.addEncodedQuery("table_sys_id=" + incRef.getUniqueValue() + "^sys_idIN" + incRef.getValue("u_attachments"));
				sysAttRef.query();
				gs.log("attachment metadata rows = " + sysAttRef.getRowCount(), source);
				while (sysAttRef.next()) {
					createAttachment(source, probRef, sysAttRef);
				}
			}
		}
		
	} catch (error) {
		gs.log("error = " + error, source);
	}
}("inc_prb_attachment");

function createAttachment(source, targetRef, sysAttRef) {
	
	try {
		var glideSysAttachmentRef = new GlideSysAttachment();
		var guid = "";
		guid = glideSysAttachmentRef.writeContentStream(targetRef, sysAttRef.getValue("file_name"), sysAttRef.getValue("content_type"), glideSysAttachmentRef.getContentStream(sysAttRef.getUniqueValue()));
		gs.log("createAttachment --> guid = " + guid, source);
	} catch (error) {
		gs.log("createAttachment --> error = " + error, source);
	}
}

Regards,

Kshitij