Skip to main content

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
1
package com.company;
2
3
import com.psddev.cms.db.Content;
4
import com.psddev.dari.util.StorageItem;
5
6
public class Image extends Content {
7
8
private StorageItem file;
9
10
public StorageItem getFile() {
11
return file;
12
}
13
14
public void setFile(StorageItem file) {
15
this.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
(() => {
10
const fileSelector = document.getElementById('file-selector');
11
fileSelector.addEventListener('change', (event) => {
12
13
const file = event.target.files[0];
14
const query = 'mutation MyMutation($file: Upload!) { com_company_ImageSave( diffs: [{ ' +
15
'com_company_ImageDiff: { file: { file: $file } } }] ) { file { path } }}'
16
const variables = { file: null }
17
const operations = { query, variables }
18
const map = { 0: ['variables.file'] }
19
20
const formData = new FormData();
21
formData.append('operations', JSON.stringify(operations))
22
formData.append('map', JSON.stringify(map))
23
formData.append('0', file, file.name)
24
25
fetch('<API_ENDPOINT_URL>', {
26
method: 'POST',
27
headers: {
28
'x-api-key': '<API_KEY>'
29
},
30
body: formData,
31
})
32
.then(response => response.json())
33
.then(responseData => {
34
console.log('Success:', responseData);
35
document.body.innerHTML = '<div>Upload Successful!</div>'
36
})
37
.catch((error) => {
38
console.error('Error:', error);
39
});
40
});
41
})();
42
</script>
43
</body>
44
</html>