I'm trying to upload a file or image on a D9 site via json api. The test is namely to upload the user picture on the user entity.
I've been following the documentation or read questions about, but I can't get it working.
The front-end is done with Next.js.
One the test done is the following:
The front-end next calls the next.js api server:
const filename = selectedFile.name;
const fr = new FileReader();
fr.readAsArrayBuffer(selectedFile);
fr.onload = async function () {
const arrayBuffer = fr.result;
if (arrayBuffer && typeof arrayBuffer !== 'string') {
const base64String = _arrayBufferToBase64(arrayBuffer);
const cookieSession = await getUpdateCookie();
const res = await fetch(`/api/users-test/user?cookie=${cookieSession}&name=${filename}`, {
method: 'POST', body: base64String,
});
}
}
function _arrayBufferToBase64(buffer: ArrayBuffer) {
let binary = '';
const bytes = new Uint8Array(buffer);
const len = bytes.byteLength;
for (let i = 0; i < len; i++) {
binary += String.fromCharCode(bytes[i]);
}
return window.btoa(binary);
}
The api next.js server post then to Drupal:
const res = await fetch(
`${process.env.NEXT_PUBLIC_DRUPAL_BASE_URL}/jsonapi/user/user/{userID}/user_picture`,
{
method: 'POST',
headers: {
'Content-Type': 'application/octet-stream',
Accept: 'application/vnd.api+json',
'Content-Disposition': `name="file"; filename="${filename}"`,
Authorization: `Bearer ${token}`,
},
body: req.body,
}
);
I tried different ways to convert the file to "binary file data", but none work: the user picture is always a blank square with an X.
However, if I try the same call with postman, the file is correctly loaded:
So, for now, I hypothesize the problem is on the javascript code, while Drupal has been configured correctly.