how to create attachment in sys_attachment table from payload
- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-18-2023 10:10 PM
Hi,
I have a payload from which I want to initialize and create an attachment in the sys_attachment table. The table sys_id and table name is a73d38761b55b9906b89a642b24bcbff and sc_cart_item. Could you please help on how to initialize and create an attachment from the json payload in sys_attachment table.
{
"payload": "", //base64 format already given
"file_name": "d.xlxs",
"content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"encoding": "base64"
}
Can you please help on the scripting part?

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-19-2023 01:50 AM - edited 09-19-2023 01:51 AM
the script does not need a Attachment record, only the sc_cart_item record, where you want to insert the Attachment.
The JSON string you can parse with JSON.parse() - for me unclear where this JSON comes from and how you want to trigger the Script? Is it a Scripted Rest API or how the JSON come to the system?
Nevertheless you only need to parse the JSON string:
var jsonstring = '{
"payload": "", //base64 format already given
"file_name": "d.xlxs",
"content_type": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
"encoding": "base64"
}';
var obj = JSON.parse(jsonstring ); //parse the JSON string to get an Javascript object
var attachment = new GlideSysAttachment();
var rec = new GlideRecord('sc_cart_item');
var sc_cart_itemSysID = 'a73d38761b55b9906b89a642b24bcbff ';
rec.get(sc_cart_itemSysID);
var fileName = obj.file_name;
var contentType = obj.content_type; //here comes the MIME Type
var base64Encodedcontent = obj.payload; //HERE comes the payload in
var agr = attachment.writeBase64(rec, fileName, contentType, base64Encodedcontent);
gs.info('The attachment sys_id is: ' + agr);
Greets
Daniel
Please mark reply as Helpful/Correct, if applicable. Thanks!

- Mark as New
- Bookmark
- Subscribe
- Mute
- Subscribe to RSS Feed
- Permalink
- Report Inappropriate Content
09-19-2023 03:10 AM - edited 09-19-2023 04:01 AM
@tanz Without any record makes no sense - an Attachment is always attached to a record - otherwise no one can see and open this. I recommend to create at least a Datasource (sys_data_source) record from type File, File retrieval method Attachment and format Excel and add this to this record. Or for testing purposes create a Incident. In your first reply you mentioned a sc_cart_item record - this could also be used. At least create any record in the system there you attach this Excel from JSON.Greets
Daniel
Please mark reply as Helpful/Correct, if applicable. Thanks!