I am trying to use box API( box upload file reference) in servicenow. This code below succeeds in uploading but the uploaded content is corrupted and unreadable.
// Create a new RESTMessageV2 object
var r = new sn_ws.RESTMessageV2();
r.setEndpoint('https://upload.box.com/api/2.0/files/content');
r.setHttpMethod('POST');
// Set the authorization header
r.setRequestHeader('Authorization', 'Bearer <dev auth code>');
// Define the boundary string
var boundary = '----WebKitFormBoundary7MA4YWxkTrZu0gW';
// Set the Content-Type header with the boundary
r.setRequestHeader('Content-Type', 'multipart/form-data; boundary=' + boundary);
// Define the attributes part of the multipart body
var attributes =
'--' + boundary + '\r\n' +
'Content-Disposition: form-data; name="attributes"\r\n\r\n' +
'{"name": "schedule1.txt", "parent": {"id": "0"}}\r\n';
// Define the file part of the multipart body
var file =
'--' + boundary + '\r\n' +
'Content-Disposition: form-data; name="file"; filename="schedule1.txt"\r\n' +
'Content-Type: text/plain\r\n\r\n' +
'BASE64_ENCODED_FILE_CONTENT' + '\r\n' +
'--' + boundary + '--\r\n'; // Closing boundary
var requestBody;
// Set the full request body (attributes and file parts)
requestBody = attributes + file;
var gr = new GlideRecord('sys_attachment');
if (gr.get('sys_id', '91b8bb9153c11210137779a0a0490e4e')) {
var attachment = new GlideSysAttachment();
var fileContent = attachment.getBytes(gr);
var base64EncodedFile = GlideStringUtil.base64Encode(fileContent);
gs.info(base64EncodedFile);
// Replace 'BASE64_ENCODED_FILE_CONTENT' in the request body with the actual encoded content
requestBody = requestBody.replace('BASE64_ENCODED_FILE_CONTENT', base64EncodedFile);
}
r.setRequestBody(requestBody);
// Execute the REST call
var response = r.execute();
var responseBody = response.getBody();
gs.info('Response: ' + responseBody);
I know what GlideStringUtil.base64Encode
does is wrong so I also tried without using it but the content is something like this: cB@4f675ae
which is not an actual readable text.
I have used new java.io.ByteArrayInputStream()
as well but didn't work either. How can I send a file that is fetched from servicenow table to box?
I tried using writeString, also using Packages.java.lang.String
The uploaded content is all corrupted, cannot open it in box console.Unreadable file, after downloading Unreadable file, before downloading
I know this question is a bit off from box but since it is urgent I am desperate…
I am asking the same question in Servicenow Community and Stackoverflow as well.