Attachment API - Retrieve Attachment Content

lookman
Kilo Expert

The Attachment API - Retrieve Attachment Content method returns the attachment content as a binary representation in a text field (the response body).

I was hoping to save the response body as the attachment itself rather than using the Retrieve Metadata for Attachments method to get the download URL. This requires extra steps to issue the GET URL, sign in, and download the file.

I have tried this but the binary data does not work as hoped. Has someone out there has done this successfully.

Any help would be very much appreciated.

jack

4 REPLIES 4

Michael Nau
Mega Guru

Not quite sure if I understand what you mean - you need the sys_id of an attachment for both GET requests in the Attachment API. So if you don't need metadata, you can issue a GET to /now/attachment/{sys_id}/file right away. However, without metadata you don't know the content type or the name of the file.

How you turn the byte array into a file depends on the client you're using.

In Powershell, it works like this:

$Uri = "https://[instance_name].service-now.com/api/now/attachment/[sys_id]/file"
$File = Invoke-WebRequest -Uri $Uri -Method Get -Credential $Cred [System.IO.File]::WriteAllBytes(".\filename.foo", $File.Content)

lookman
Kilo Expert

Hi Michael.

Thank you for the response. I have the sys_id and I'm using the method suggested. The issue I'm having is that the binary code response I'm getting is not working as expected.

When I write he output to a file, it is not the same as what I uploaded.

In my example, I uploaded a PDF file to an incident using the UI. Using /now/attachment/{sys_id}/file I get the response body, which is a binary representation of the file.

Using the PowerShell code that the REST API Explorer provided, I write the file. When I look at it, it does not open as expected, PDF viewer throwing an error.

I wasn't sure if anyone else had issues writing the binary files and if so, did they have to do anything with encoding or something else.

 

jack

shiven
Tera Contributor

Hello @lookman , I am facing the same issue, looking for ways to get the file back from binary content.

 

lookman
Kilo Expert

Hi Shiven. I put this issue aside and have not looked at it since. If you find a solution, please let me know.

 

jack