The CreatorCon Call for Content is officially open! Get started here.

Need to read a file from the local machine and upload the file on the servicenow record

Shweta
Tera Contributor

Hello All,

I want to read the file from the local machine and upload the file into the servicenow record.

To achieve this, I have followed steps 1. Read the file and convert it to a base64 encoded string. 2. Decode the string and write it to the record. I have created a Scripted API with the following code:

(function process( /*RESTAPIRequest*/ request, /*RESTAPIResponse*/ response) {

var tableName = request.queryParams.tableName;
var number = request.queryParams.number;
var fileName = request.queryParams.fileName;
var fileMimeType = request.headers.mimetype;
var fileData = request.body.dataStream;

var rec = new GlideRecord(tableName);
rec.addQuery('number', number);
rec.query();
if (rec.next()) {var sa = new GlideSysAttachment();
var base64string = GlideStringUtil.base64Encode(fileData);
//var base64string = gs.base64Encode(fileData);

var decodedString = GlideStringUtil.base64Decode(base64string);
//var decodedString = gs.base64Decode(base64string);

sa.write(rec, fileName, fileMimeType, decodedString);

var responseBody = {};
responseBody.number = number;
responseBody.status = "Success";
response.setBody(responseBody);
} else {
var responseBodyFailure = {};
responseBodyFailure.status = "Success";
response.setBody(responseBodyFailure);
}

})(request, response);

 

However, I am facing two issues with this code:

1. By executing this code in my PDI the file is getting uploaded successfully however the files seems to be blank when opened.

2. I have moved the same code into my customer environment, however it gives me an error "Cannot find function base64Encode in object function GlideStringUtil()". Therefore I used gs.base64Encode(fileData) and gs.base64Decode(base64string); in the above code. This creates the same issue mentioned in 1st point i.e. the file is getting uploaded successfully however the files seems to be blank when opened.

 

Please suggest to me if I am missing anything.

Thank you,

Shweta

15 REPLIES 15

Can you add the gs.log(fileData) after the while loop and share with me the output

Thank you,
Palani

Following is te output:

{"dataStream":"C:\Users\shwetak\Desktop\ShwetaTS.pdf"}

find_real_file.png

Is this the data are you planning to add to attachment? File stream is returning this value.

Thank you,
Palani

Hello,

C:\Users\shwetak\Desktop\ShwetaTS.pdf is the path where the attachment is located. I am passing {"dataStream":"C:\Users\shwetak\Desktop\ShwetaTS.pdf"} into the body of the Scripted API call.

How are you sending data from local machine to ServiceNow? are you using postman or any other tool?

Share me how are you calling the Rest API. Not sure whether data is passed properly

Thank you,
Palani