Working With Files in the Ninox API: Part 3

By Adam Davidson, Director of Product Development

This time around we will be downloading a file to the user’s device from javascript inside a Ninox formula field.  Please see Part 2 of this series for background, as this article builds on the code there.  

We will modify the code from last week to add a button below each of the file names wwe retrieve from the API.  when the button is clicked, another API call can be made to download the file.

					html(" <script>let downloadFile=(fileName)=>{let headers={'Authorization':'Bearer '+'" + apiKey() + "'};let url='" + teamId() + "/databases/" + databaseId() + "/tables/" + tableId(this) + "/records/" + Id + "/files/'+fileName;fetch(url,{headers:headers}).then(response=>response.blob()).then(blob=>{var url=window.URL.createObjectURL(blob);var a=document.createElement('a');a.href=url;;document.body.appendChild(a);;a.remove()})}
let getFiles=()=>{let headers={'Authorization':'Bearer '+'" + apiKey() + "'};let url='" + teamId() + "/databases/" + databaseId() + "/tables/" + tableId(this) + "/records/" + Id + "/files';console.log('hello Adam');fetch(url,{headers:headers}).then(response=>response.json()).then(files=>{let container=document.getElementById('files_conatiner');let html=''
for(let file of files){html+='<div>''</div><button onclick=""downloadFile(\'''\')"">download</button>'}
container.innerHTML=html})}</script> <style onload='getFiles()'></style><div id='files_conatiner' onclick='getFiles()'>hello</div>


The button function above, “downloadFile” takes the file’s name and makes a request to the API to get the file. The file is passed to the code as a binary stream. In order to have the file downloaded to the user’s device we have to employ a trick. We create a link element (<a>) which is a download type link. Link elements with a download attribute download the contents of HTTP response to the user’s device rather than opening them in the browser. The Code above “clicks” the link element and then removes it from the page, which downloads the file.

Now we have a list of files attached to the current record in the formula field with a functioning download button for each!