Attachment Upload Rest API - JAVA

arjun6080
Kilo Explorer

Hello ,

I am trying to upload an attachment to an ticket using below JAVA code.

String postData = "{\"table_name\":\"u_portal\",\"table_sys_id\":\"091feee8ab18110c778\",\"uploadFile\":\"/ServiceNow_Rest/src/com/servicenow/integration/upload1.JPG\"}";

  CredentialsProvider credsProvider = new BasicCredentialsProvider();

  credsProvider.setCredentials(new AuthScope(new HttpHost("service-now.com")),

  new UsernamePasswordCredentials("name", "pwd"));

  CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();

  try {

  HttpPost httpPost = new HttpPost("https://service-now.com/api/now/attachment/upload");

  httpPost.setHeader("Accept", "application/json");

  httpPost.setHeader("Content-Type", "multipart/form-data");

  HttpEntity entity = new ByteArrayEntity(postData.getBytes("utf-8"));

  httpPost.setEntity(entity);

  System.out.println("Executing request " + httpPost.getRequestLine());

  CloseableHttpResponse response = httpclient.execute(httpPost);

  try {

  System.out.println("----------------------------------------");

  System.out.println(response.getStatusLine());

  String responseBody = EntityUtils.toString(response.getEntity());

  System.out.println(responseBody);

....

Getting

HTTP/1.1 400 Bad Request

{"error":{"detail":null,"message":"Failed to create the attachment. File part might be missing in the request."},"status":"failure"}

can someone help on this ?

Regards,

13 REPLIES 13

Alikutty A
Tera Sage

It says attachment missing, something wrong in the way you upload the attach. You should try the other post method which work with the binary.



https://docs.servicenow.com/bundle/helsinki-servicenow-platform/page/integrate/inbound-rest/referenc...



Thank You


Please Hit Like, Helpful or Correct depending on the impact of response


Community Alums
Not applicable

Hi Mallikarjun,


Can you send file as   base64 bytes.



Thanks,


Rajendra Prasad Darshanam


arjun6080
Kilo Explorer

No Lucks ...



Anyone having JAVA sample example to upload attachment ?


andynowack
Kilo Contributor

1. Don't set the header with multipart/form-data
//httpPost.setHeader("Content-Type","multipart/form-data"); // you dont need this



2. Use MultipartEntityBuilder with addPart: sys_id, table_name and binaryData


HttpEntity reqEntity = MultipartEntityBuilder.create()


.addPart("table_sys_id",SNOW_sys_id)


.addBinaryBody("uploadFile", UpFile, ContentType.DEFAULT_BINARY, UpFile.getName())



Upload works fine, My result:


{"result":{"size_bytes":"110641","file_name":"XXX.png","sys_mod_count":"0","average_image_color":"","image_width":"","sys_updated_on":"2017-06-14 07:22:17","sys_tags":"","table_name":"kb_knowledge","sys_id":"51e622524f97b2009fe5eb118110c7a3","image_height":"","sys_updated_by":"aa","download_link":"https://XXX.service-now.com/api/now/attachment/51e622524f97b2009fe5eb118110c7a3/file","content_type":"application/octet-stream","sys_created_on":"2017-06-14 07:22:17","size_compressed":"109033","compressed":"true","table_sys_id":"e2906aac4f1f32009fe5eb118110c78b","sys_created_by":"aa"}}


bgworld
Giga Expert

Hi arjun6080 ,



Here is the example to post file to sn using attachment multipart api:


public static void main(String[] args) throws Exception {



try {


System.out.println("Starting Post Request.....");


CredentialsProvider credsProvider = new BasicCredentialsProvider();


UsernamePasswordCredentials credentials = new UsernamePasswordCredentials("username", "password");


credsProvider.setCredentials(AuthScope.ANY, credentials);



CloseableHttpClient httpclient = HttpClients.custom().setDefaultCredentialsProvider(credsProvider).build();


HttpPost httppost = new HttpPost("https://<myservicenow>.service-now.com/api/now/attachment/upload");


httppost.setHeader("Accept", "application/json");


//httppost.setHeader("Content-Type", ContentType.MULTIPART_FORM_DATA.getMimeType()+"; boundary=--BGBoundary_vs3IYA_fjfkCUSlqhY");


httppost.setHeader("Accept-Encoding", "gzip, deflate, br");



//build multipart request


String textFileName = "/Users/brajendragupta/Documents/Web/REST/incident.xlsx";


File file = new File(textFileName);


MultipartEntityBuilder builder = MultipartEntityBuilder.create();


builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);


FileBody fileBody = new FileBody(file, ContentType.DEFAULT_BINARY);


StringBody stringBody1 = new StringBody("sys_data_source", ContentType.MULTIPART_FORM_DATA);


StringBody stringBody2 = new StringBody("287379e11391cb00e9c059722244b0d6", ContentType.MULTIPART_FORM_DATA);


builder.addPart("table_name", stringBody1);


builder.addPart("table_sys_id", stringBody2);


builder.addPart("file", fileBody);



httppost.setEntity(entity);


//---Print outgoing request---


Header[] headers = httppost.getAllHeaders();


String content = EntityUtils.toString(entity);


System.out.println(httppost.toString());


for (Header header : headers) {


System.out.println(header.getName() + ": " + header.getValue());


}


System.out.println();


System.out.println(content);


//----execute http request


HttpResponse response = httpclient.execute(httppost);


System.out.println("HTTP POST response:");


System.out.println(response.getStatusLine());


String responseBody = EntityUtils.toString(response.getEntity());


System.out.println(responseBody);



} catch (Exception e) {


System.err.println("Unable to read file");


e.printStackTrace();


}


}