Skip to content

Instantly share code, notes, and snippets.

@srkirkland
Created August 2, 2022 20:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save srkirkland/017a0909a7fab4b109fe992899dd0f30 to your computer and use it in GitHub Desktop.
Save srkirkland/017a0909a7fab4b109fe992899dd0f30 to your computer and use it in GitHub Desktop.
Example of uploading an audio file to drupal via JSONAPI
import fetch from "node-fetch";
// env vars
const apiUser = "apiuser";
const apiPass = "pass";
const baseUrl = "https://example.org/jsonapi";
const auth = "Basic " + Buffer.from(`${apiUser}:${apiPass}`).toString("base64");
/* This snippet:
1. takes a sample MP3 url and downloads it
2. uploads the audio to your drupal instance as a "file"
3. creates a media object associated with that file, so it can be used later
*/
const testMp3Url =
"https://download.samplelib.com/mp3/sample-6s.mp3";
const createMediaItem = async (uuid, fileName) => {
const url = baseUrl + "/media/sf_audio_media_type";
const jsonApiData = {
data: {
type: "media--sf_audio_media_type",
attributes: {
status: true,
name: fileName,
},
relationships: {
field_media_audio_file: {
data: {
type: "file--file",
id: uuid
},
},
},
},
};
const jsonApiRequest = await fetch(url, {
method: "POST",
headers: {
Accept: "application/vnd.api+json",
"Content-Type": "application/vnd.api+json",
Authorization: auth,
},
body: JSON.stringify(jsonApiData),
});
if (jsonApiRequest.ok) {
const jsonApiResponse = await jsonApiRequest.json();
console.log("Media item created", jsonApiResponse);
} else {
console.log("Error creating media item", jsonApiRequest.status, jsonApiRequest.statusText);
}
};
const uploadMedia = async () => {
const url = baseUrl + "/media/sf_audio_media_type/field_media_audio_file";
// get raw buffer of audio file
const audioRequest = await fetch(testMp3Url);
const audioBuffer = await audioRequest.buffer();
const fileName = "test5.mp3";
// Step 2: Upload audio to SiteFarm media
const uploadRequest = await fetch(url, {
method: "POST",
headers: {
Accept: "application/vnd.api+json",
"Content-Type": "application/octet-stream",
"Content-Disposition": 'file; filename="' + fileName + '"',
Authorization: auth,
},
body: audioBuffer,
});
if (uploadRequest.ok) {
const uploadData = await uploadRequest.json();
const mediaId = uploadData.data.id;
console.log("Upload successful", uploadData);
await createMediaItem(mediaId, fileName);
} else {
console.log("Upload failed");
}
};
uploadMedia()
.then(() => console.log("done"))
.catch(console.error);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment