saveResponseBodyAsAttachment not working

charanya
Tera Contributor

I am trying to download a file from API response and attach it to a task record. The below is my code. Everything is working fine and the file is also getting attached to the task record. But the file is not loading. If i open it in a separate tab, the file is getting downloaded and also loading as it should. But via the below code, download & attachment happens but the file is not loading as it should when i open it. If its xlsx file, it says 'Excel cannot open the file because file format or file extension is not valid. Verify the file has not been corrupted and that the file extension matches the format of the file.' 

But it opens well when i open it as a separate link.

 

var tablename  = 'sc_task';
var recordSysId = '25ce1d6d47325510725600752344556'; //TASK0009464695
var filename  = 'FileTEST.xlsx';

var TestFile = '<file link>';
var request = new sn_ws.RESTMessageV2();
request.setHttpMethod('get');
request.setEndpoint(TestFile);

request.saveResponseBodyAsAttachment(tablename, recordSysId, filename);
var response = request.execute();


var httpStatus = response.getStatusCode();
gs.print(httpStatus);
gs.print(response.haveError());
gs.print(response.getResponseAttachmentSysid());
gs.print(response.getHeader('Content-Type'));
gs.print(response.getErrorMessage());

 

Thanks in advance.

1 REPLY 1

Tony Chatfield1
Kilo Patron

Hi, perhaps the sys_attachment content type is being set incorrect\doesn't match the file.
Have you tried the process with simple file like cvs (not created in excel) or plain text to see if they work correctly?

 

Edit:

If it is the content type, I have had similar issue in the past and to resolve it I followed the sys_attachment insert process with a GlideRecord query to the new record and set the content type based on source details, but you could also map it by file type\file name suffix or try a default of 'application/octet-stream' or  set it empty (and see if it helps).

 - I was able to map most of my content with a REST query to the source file structure before I downloaded the attachment.