File/Image Uploads

Uploading a file or image via the Knack API is a two step process. The first will perform an HTTP POST request with a multipart/form-data content type to the following URL: https://api.knack.com/v1/applications/app_id/assets/file/upload

The second step is to then create a new record using the information from the response in the first step.

1. Uploading the File

The following is a cURL request which uploads a file (replace “file” with “image” when uploading an image file):

curl -X POST "https://api.knack.com/v1/applications/YOUR-APP-ID/assets/file/upload" \
  -H 'content-type: multipart/form-data' \
  -H 'x-knack-rest-api-key: YOUR-API-KEY' \
  -H 'x-knack-application-ID: YOUR-APP-ID'\
  -F "[email protected]/path/to/your/file.txt"

File uploading can also be done via JavaScript/AJAX (replace “file” with “image” when uploading an image file):

var app_id = Knack.application_id;

    var form = new FormData();
    // change #myfileinput to select your <input type="file" /> element
    var file = $(`#myfileinput`)[0].files[0];
    form.append(`files`, file);

    var url = `https://api.knack.com/v1/applications/${app_id}/assets/file/upload`;
    var headers = {
      'X-Knack-Application-ID': app_id,
      'X-Knack-REST-API-Key': `knack`,
    };

    Knack.showSpinner();

    // Make the AJAX call
    $.ajax({
      url: url,
      type: `POST`,
      headers: headers,
      processData: false,
      contentType: false,
      mimeType: `multipart/form-data`,
      data: form,
    }).done(function(responseData) {
      console.log(responseData);
      Knack.hideSpinner();
    });

A successful POST will return the following JSON response representing details about the uploaded file:

{
  "id": "YOUR-FILE-ID",
  "type": "file",
  "filename": "file.txt",
  "public_url": "https://api.knack.com/v1/applications/YOUR-APP-ID/download/asset/YOUR-FILE-ID/file.txt",
  "thumb_url": "",
  "size": 12043
}

2. Creating the Record

This response contains an id property that you will use in the next step. The public_url property will contain a direct link to the file itself, and the thumb_url property will contain a link to a thumbnail if an image was uploaded.

Use the file_id from the JSON response to make a second POST request to create a record referencing your file. Set that file_id to your image or file field.

The following is a cURL example, assuming field_1 is a file or image field:

curl -X POST "https://api.knack.com/v1/objects/object_xx/records" \
  -H "x-knack-rest-api-key: YOUR-API-KEY" \
    -H "x-knack-application-id: YOUR-APP-ID" \
    -H "content-type: application/json" \
    --data '{"field_1": "YOUR-FILE-ID"}'

Did this page help you?