REST Attachment currupted file

jacobo
Tera Contributor

Hi All

 

I need to send an excel file to an external API with post method. I'm using  this code to send it I have a successful result , the excel file is attached in the client environment (it is not servicenow)
When I try to download the attachemtent , excel can't open it beacuse the file is corrupted

 

Do you know what could be the possible error on my script?

 

Regards

 

var attachment = new GlideSysAttachment();
 
var agr = attachment.getAttachments('sc_req_item', 'ab480111c368ea9cda547fe4e4013143');
 
while(agr.next())
gs.info(agr.getValue('file_name'));
gs.info(agr.getValue('sys_id'));
 
var Attachname = agr.getValue('file_name');
var attachmentSysId = agr.getValue('sys_id');
 
var attach=""    
var is = new GlideSysAttachment().getContentStream(attachmentSysId);
var reader = new GlideTextReader(is);
var attachmentData = ' ';
while((attachmentData = reader.readLine()) != null) {
    // gs.log(attachmentData)
attach += attachmentData+"\r\n"
}
    // Define a boundary for the multipart/form-data request
    var boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
    
    // Build the multipart body string
    var body = '';
    // File part: adjust the "name" and "filename" as needed
    body += '--' + boundary + '\r\n';
    body += 'Content-Disposition: form-data; name="files"; filename="'+Attachname+'"\r\n';
    body += 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n';
    // Append the file content. Note: if you need to send Base64 instead, retrieve and append Base64 content.
    body += attach;
    body += '\r\n';
    // End boundary
    body += '--' + boundary + '--\r\n';
 
    // Create and configure the REST message
    var restMessage = new sn_ws.RESTMessageV2();
    restMessage.setHttpMethod('POST');
    restMessage.setLogLevel('all')
    restMessage.setEndpoint(External URL);
    restMessage.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
   gs.log(body)
    restMessage.setRequestBody(body);
 
    try {
        // Execute the REST call and log the response
        var response = restMessage.execute();
        var responseBody = response.getBody();
        gs.info('Response: ' + responseBody);
    } catch(e) {
        gs.error('Error sending Excel attachment: ' + e);
    }
 
7 REPLIES 7

Shivalika
Mega Sage
Mega Sage

Hello @jacobo 

 

You are using this script to post data on that side right ? WHy are you using the same script to download data on your end ? I mean were you also using the endpoint and tried downloading the attachment that's added. 

 

Sorry, Question is unclear to me. 

 

Kindly mark my answer as helpful and accept solution if it helped you in anyway. This will help me be recognized for the efforts and also move this questions from unsolved to solved bucket. 

 

Regards,

 

Shivalika 

 

My LinkedIn - https://www.linkedin.com/in/shivalika-gupta-540346194

 

My youtube - https://youtube.com/playlist?list=PLsHuNzTdkE5Cn4PyS7HdV0Vg8JsfdgQlA&si=0WynLcOwNeEISQCY

jacobo
Tera Contributor

Hi

 

I used the code to send the attachment then I will go to the user environment and I downloaded it manually

 but whe I try to open it , I have this error message

 

jacobo_0-1743803058904.pngjacobo_1-1743803084137.png

 

I don't really what happened

 

Hello @jacobo 

 

Ok I got it , there is some data here that's not to be in Excel. It's not decoding properly for Excel format. I am aware about  function maybe try that - 

 

Try below 👇 script - 

 

var attachment = new GlideSysAttachment();

 

var agr = attachment.getAttachments('sc_req_item', 'ab480111c368ea9cda547fe4e4013143');

 

while (agr.next()) {

    gs.info(agr.getValue('file_name'));

    gs.info(agr.getValue('sys_id'));

 

    var Attachname = agr.getValue('file_name');

    var attachmentSysId = agr.getValue('sys_id');

 

    var boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';

 

    var bodyHeader = '';

    bodyHeader += '--' + boundary + '\r\n';

    bodyHeader += 'Content-Disposition: form-data; name="files"; filename="' + Attachname + '"\r\n';

    bodyHeader += 'Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet\r\n\r\n';

 

    var bodyFooter = '\r\n--' + boundary + '--\r\n';

 

    var restMessage = new sn_ws.RESTMessageV2();

    restMessage.setHttpMethod('POST');

    restMessage.setLogLevel('all');

    restMessage.setEndpoint('External URL');

    restMessage.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);

 

    // Set the first part of body

    restMessage.setRequestBody(bodyHeader);

 

    // Attach the file content directly (raw binary)

    restMessage.setRequestBodyFromAttachment(attachmentSysId);

 

    // Append the footer manually (after the binary)

    restMessage.setStringParameterNoEscape('body_end', bodyFooter);

 

    try {

        var response = restMessage.execute();

        var responseBody = response.getBody();

        gs.info('Response: ' + responseBody);

    } catch (e) {

        gs.error('Error sending Excel attachment: ' + e);

    }

 

    break; // only handle the first attachment

}

 

Kindly mark my answer as helpful and accept solution if it helped you in anyway. This will help me be recognized for the efforts and also move this questions from unsolved to solved bucket. 

 

Regards,

 

Shivalika 

 

My LinkedIn - https://www.linkedin.com/in/shivalika-gupta-540346194

 

My youtube - https://youtube.com/playlist?list=PLsHuNzTdkE5Cn4PyS7HdV0Vg8JsfdgQlA&si=0WynLcOwNeEISQCY

Shivalika
Mega Sage
Mega Sage

Hello @jacobo 

 

Please confirm if you checked my answer. Kindly mark my answer as helpful and accept solution if it helped you in anyway. This will help me be recognized for my efforts and also it can move from unsolved bucket to solved bucket. 

 

Regards, 

Shivalika 

 

My LinkedIn - https://www.linkedin.com/in/shivalika-gupta-540346194

 

My youtube - https://youtube.com/playlist?list=PLsHuNzTdkE5Cn4PyS7HdV0Vg8JsfdgQlA&si=0WynLcOwNeE