Decode base64 field and add to record as attachment

rcard11
Tera Guru

I have a field on a case form that is populated with a base64 value.  I would like to take that string and convert it back into an image and attach that image to the case.  Has anyone had any success in doing this?  Thank you in advance for your help!

10 REPLIES 10

Ratnakar7
Mega Sage
Mega Sage

Hi @rcard11 ,

 

Yes, it is possible to decode a base64 string, convert it into an image, and attach it to a record in ServiceNow. You can achieve this by using server-side scripting in a business rule or a script include. Here's an example of how you can do it:

  1. Create a business rule or a script include: Navigate to "System Definition" > "Business Rules" or "System Definition" > "Script Includes" and create a new business rule or script include, respectively.

  2. Write the script: In the script, you'll need to decode the base64 string, create an attachment record, and attach the decoded image to it. Here's an example script:

 

// Get the base64 string from the field on the case record
var base64String = current.field_name; // Replace 'field_name' with the actual field name

// Decode the base64 string into a byte array
var base64Bytes = GlideStringUtil.base64DecodeAsBytes(base64String);

// Create an attachment record
var attachment = new GlideSysAttachment();
attachment.setFileName("image.jpg"); // Set the desired file name for the attachment
attachment.setTableName(current.getTableName());
attachment.setTableSysId(current.getUniqueValue());

// Attach the decoded image to the attachment record
attachment.writeBase64Content(base64Bytes);

// Insert the attachment record
attachment.insert();

 

Make sure to replace 'field_name' with the actual field name on the case record where the base64 string is stored. Also, adjust the file name as per your requirement.

      3. Save the business rule or script include: After writing the script, save the business rule or script include.

      4. Trigger the script: The script will be triggered whenever a case record is updated or whenever the business rule is configured to run. The base64 string will be decoded, and the image will be attached to the case record as an attachment.

Please note that this example assumes you're using JavaScript on the server-side in ServiceNow. If you're using a different scripting language or a different platform, the code may vary slightly.

 

Thanks,

Ratnakar

Thanks Ratnaker.  I am getting this message when the business rule runs on the record:

 

Error Message

Illegal access to method setFileName(string) in class com.glide.ui.SysAttachment

rcard11
Tera Guru

@Ankur Bawiskar Thanks in advance for your help!

 

@rcard11 

can you share your complete script and screenshots?

Regards,
Ankur
Certified Technical Architect  ||  9x ServiceNow MVP  ||  ServiceNow Community Leader