Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

attach attachment to Incident along with more details from REST api

Prateek1
Tera Contributor

I am working on thing in Scripted REST API to create incident along with attachment which could be in any format ( file type, name along extension & base64 encoded string ) provided by 3rd part (.net program). i am unable decode it to base64 and attach it to INC any help on this is welcomed. Thanks in advance .

1 ACCEPTED SOLUTION

SwathiPedireddy
Kilo Sage

Hi @Prateek1 

Try following script

var attachment_name = ;//attachment name with extension
var contentType = ;//content type of the file(optional)

var incident_id = "sys_id of the incident";
var stringUtil = GlideStringUtil;
var attachment = new Attachment();
var value = attachment.write('incident', incident_id, attachment_name, contentType, stringUtil.base64DecodeAsBytes(base64 encoded string));

Thanks,

Swathi

View solution in original post

4 REPLIES 4

SwathiPedireddy
Kilo Sage

Hi @Prateek1 

Try following script

var attachment_name = ;//attachment name with extension
var contentType = ;//content type of the file(optional)

var incident_id = "sys_id of the incident";
var stringUtil = GlideStringUtil;
var attachment = new Attachment();
var value = attachment.write('incident', incident_id, attachment_name, contentType, stringUtil.base64DecodeAsBytes(base64 encoded string));

Thanks,

Swathi

worked for image/png will test this out and accept as solution . Thanks for quick response

Hi @Prateek1 

Please accept as solution if it works for you

 

Thanks,

Swathi

Sumanth16
Kilo Patron

Hi @Prateek1 ,

 

 

Sample JSON request:

{
  "incidentNumber": "incident number here",
  "fileName": "my file.txt",
  "contentType": "text/plain",
  "fileData": "my sample file"
}

Scripted REST API Script:

(function process(/*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

	var requestBody = request.body.dataString;
	var parser = new global.JSON();
	var parsedData = parser.decode(requestBody);
	var number = parsedData.incidentNumber;
	var fileName = parsedData.fileName;
	var fileContentType = parsedData.contentType;
	var fileData = parsedData.fileData;

	var rec = new GlideRecord('incident');
	rec.addQuery('number',number);
	rec.query();
	if(rec.next()){
		var sa = new GlideSysAttachment();
		sa.write(rec, fileName, fileContentType, fileData);
		var responseBody = {};
		responseBody.incNumber = number;
		responseBody.status = "Success";
		response.setBody(responseBody);
	}
	else{
		var responseBodyFailure = {};
		responseBodyFailure.status = "Failure";
		response.setBody(responseBodyFailure);
	}

})(request, response);

 

Mark the comment as a correct answer and also helpful once worked.

 

Thanks & Regards,
Sumanth Meda