Uploading files in Brightspot Content Management API
This guide will explain how to upload files to Brightspot records via CMA GraphQL mutation APIs.
Prerequisites for uploading a file
For endpoint configuration, see Custom Content Management API development and Hello Content Management API.
Introduction to uploading a file
Being that the official GraphQL spec does not currently support upload mutations, the CMA implements a popular community extension to the specification: GraphQL multipart request specification.
Background to uploading a file
Consider the following Image content class that will store our file and be configured as a mutable entry field on our endpoint:
showLineNumbers
1package com.company;23import com.psddev.cms.db.Content;4import com.psddev.dari.util.StorageItem;56public class Image extends Content {78private StorageItem file;910public StorageItem getFile() {11return file;12}1314public void setFile(StorageItem file) {15this.file = file;16}17}
Example of uploading a file
showLineNumbers
1<!DOCTYPE>2<html lang="en">3<head>4<title>CMA StorageItem Upload Example</title>5</head>6<body>7<input type="file" id="file-selector">8<script>9(() => {10const fileSelector = document.getElementById('file-selector');11fileSelector.addEventListener('change', (event) => {1213const file = event.target.files[0];14const query = 'mutation MyMutation($file: Upload!) { com_company_ImageSave( diffs: [{ ' +15'com_company_ImageDiff: { file: { file: $file } } }] ) { file { path } }}'16const variables = { file: null }17const operations = { query, variables }18const map = { 0: ['variables.file'] }1920const formData = new FormData();21formData.append('operations', JSON.stringify(operations))22formData.append('map', JSON.stringify(map))23formData.append('0', file, file.name)2425fetch('<API_ENDPOINT_URL>', {26method: 'POST',27headers: {28'x-api-key': '<API_KEY>'29},30body: formData,31})32.then(response => response.json())33.then(responseData => {34console.log('Success:', responseData);35document.body.innerHTML = '<div>Upload Successful!</div>'36})37.catch((error) => {38console.error('Error:', error);39});40});41})();42</script>43</body>44</html>