pdf and excel attachments are not converting from JSON. with base64decode

MaruthiVV
Tera Contributor

The issue not converting the PDF and Excel file its working only for CSV for PDF and Excel data is corrupted.

The function base64Decode is not available our environment.

 

please reply to this if any one understood the issue 

 

(function() {
// Custom Base64 Decoding Function
function base64Decode(input) {
var keyStr = "ABCDEFGHIJKMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789+/=";
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, ""); // Remove invalid Base64 characters

while (i < input.length) {
enc1 = keyStr.indexOf(input.charAt(i++));
enc2 = keyStr.indexOf(input.charAt(i++));
enc3 = keyStr.indexOf(input.charAt(i++));
enc4 = keyStr.indexOf(input.charAt(i++));

chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;

output = output + String.fromCharCode(chr1);

if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
}

// Example JSON message with Base64 encoded data

 var files = current.files.toString();

var contentType = 'application/json'; // Assume content type is JSON
var parsedData = JSON.parse(files); // Parse the JSON data in the 'files' field
var fileName = Object.keys(parsedData)[0]; // Extract the file name (assuming one file per email)
var base64Content = parsedData[fileName]; // Get the Base64 content for the file

// Log the Base64 content (for debugging purposes)
gs.info("Base64 Data: " + base64Content);

// Decode the Base64 content to its binary form
var decodedData = base64Decode(base64Content);

// Determine MIME type based on file extension
var mimeType;
if (fileName.endsWith('.csv')) {
mimeType = 'text/csv';
} else if (fileName.endsWith('.pdf')) {
mimeType = 'application/pdf';
} else if (fileName.endsWith('.xls')) {
mimeType = 'application/vnd.ms-excel';
} else if (fileName.endsWith('.xlsx')) {
mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
} else {
mimeType = 'application/octet-stream'; // Default for unknown types
}

// Create a dynamic file name
var timestamp = new Date().toISOString(); // Get a timestamp

// Create and attach the file to the email record with the new file name
var attachment = new GlideSysAttachment();
attachment.write(grRecord, fileName, mimeType, decodedData);
}
})();

0 REPLIES 0