Join the #BuildWithBuildAgent Challenge! Get recognized, earn exclusive swag, and inspire the ServiceNow Community with what you can build using Build Agent.  Join the Challenge.

Need help on Attachment API POST method 'service-now.com/api/now/attachment/file' using Angular 5/TypeScript - Looking for POST Request code samples

Sony V L
Mega Contributor

How can I upload Image/Excel files from my angular 5 application to Attachment table, using Attachment API POST, 'Upload an attachment from a binary request - service-now.com/api/now/attachment/file'

I have uploaded Image/Excel files but these files are corrupted when I downloaded. Please find below code

 

HTML

..........................

<input type="file" id="file" (change)="handleFileUpload($event)">
 
COMPONENT CLASS

.....................................................................
export class UploadComponent implements {
handleFileUpload(event: any) {
let fileList: FileList = event.target.files;
if(fileList.length > 0) {
let reader = new FileReader();
let file = fileList[0];
reader.readAsDataURL(file);
reader.onloadend = () => {
this.attachmentName = file.name;
this.fileType = file.type;
this.uploadFile = reader.result.split(',')[1];
 };
 }
 }
 
UploadDocumentAttachment() {

return this._service.UploadAttachment('document_table', this.docId, this.uploadFile, this.attachmentName,this.fileType)

 }
}

SERVICE CLASS

..............................................
export class UploadService {

UploadAttachment(tableName: string, tableSysId: string, uploadFile:any, attachmentName: string,fileType: string) {
    const url = '/now/attachment/file?table_name='+ tableName +'&table_sys_id=' + tableSysId + '&file_name=' + attachmentName;
    const requestUrl = `${this.BaseUrl}/${url}`;
    var byteCharacters = atob(uploadFile);
    var byteArrays= [];
    var sliceSize = 512;
    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
            var slice = byteCharacters.slice(offset, offset + sliceSize);
            var byteNumbers = new Array(slice.length);
            for (var i = 0; i < slice.length; i++) {
                      byteNumbers[i] = slice.charCodeAt(i);
            }
            var byteArray = new Uint8Array(byteNumbers);
            byteArrays.push(byteArray);
    }
    var blob = new Blob(byteArrays, {type: fileType,});

    let formData: FormData = new FormData();
    formData.append('file', blob, fileName);

        const httpOptions = {
          headers: new HttpHeaders({
            'Content-Type':  fileType,
            'Accept': 'application/json',

          })
        }
        return this._http.post(requestUrl, formData, httpOptions).catch(this.handleError);

  }
}

 

 

Thanks in advance,

Sony.

1 ACCEPTED SOLUTION

Sony V L
Mega Contributor

Hello,

When using ecc_queue it showed permission issue in production. And the below code worked fine.

 

  UploadEmailAttachment(data: any ) {
    const url = '/now/attachment/file?table_name='+ data.tableName +'&table_sys_id=' + data.tableSysid + '&file_name=' + data.fileName;
    const requestUrl = `${this.BaseUrl}/${url}`;

    var byteCharacters = atob(data.attachmentData);
    var byteArrays= [];
    var sliceSize = 512;
    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
              var slice = byteCharacters.slice(offset, offset + sliceSize);
                 var byteNumbers = new Array(slice.length);
                 for (var i = 0; i < slice.length; i++) {
                       byteNumbers[i] = slice.charCodeAt(i);
                 }
             var byteArray = new Uint8Array(byteNumbers);
       byteArrays.push(byteArray);
       }
    var blob = new Blob(byteArrays, {type: data.fileType,});

    return this._http.post(requestUrl, blob).catch(this.handleError);
  }

 

Thanks.

Sony.

 

View solution in original post

4 REPLIES 4

vkachineni
Kilo Sage

Try posting to the ecc_queue

 

This might help.

https://community.servicenow.com/community?id=community_question&sys_id=2053e5f71bd97f00d01143f6fe4bcb9f&anchor=answer_f289f604db2db3404819fb243996192a

 

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

Sony V L
Mega Contributor

Hi vkachineni,

Thank you for the response,

Any chance to get java script code samples, which is calling attachment API?

 

Thanks.

Sony.

I do not but you can try the rest explorer generated code

var requestBody = "{\"payload\":\"\",\"topic\":\"\",\"agent\":\"\"}"; 

var client=new XMLHttpRequest();
client.open("post","https://instance.service-now.com/api/now/table/ecc_queue");

client.setRequestHeader('Accept','application/json');
client.setRequestHeader('Content-Type','application/json');

//Eg. UserName="admin", Password="admin" for this code sample.
client.setRequestHeader('Authorization', 'Basic '+btoa('admin'+':'+'admin'));

client.onreadystatechange = function() { 
	if(this.readyState == this.DONE) {
		document.getElementById("response").innerHTML=this.status + this.response; 
	}
}; 
client.send(requestBody);

 

 

Please mark Correct and click the Thumb up if my answer helps you resolve your issue. Thanks!
Vinod Kumar Kachineni
Community Rising Star 2022

Sony V L
Mega Contributor

Hello,

When using ecc_queue it showed permission issue in production. And the below code worked fine.

 

  UploadEmailAttachment(data: any ) {
    const url = '/now/attachment/file?table_name='+ data.tableName +'&table_sys_id=' + data.tableSysid + '&file_name=' + data.fileName;
    const requestUrl = `${this.BaseUrl}/${url}`;

    var byteCharacters = atob(data.attachmentData);
    var byteArrays= [];
    var sliceSize = 512;
    for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
              var slice = byteCharacters.slice(offset, offset + sliceSize);
                 var byteNumbers = new Array(slice.length);
                 for (var i = 0; i < slice.length; i++) {
                       byteNumbers[i] = slice.charCodeAt(i);
                 }
             var byteArray = new Uint8Array(byteNumbers);
       byteArrays.push(byteArray);
       }
    var blob = new Blob(byteArrays, {type: data.fileType,});

    return this._http.post(requestUrl, blob).catch(this.handleError);
  }

 

Thanks.

Sony.