Skip to main content

Creating Media with Service in Drupal

First we need to know what is needed to create a media. In Drupal, media consists of files. So to create a media, we first need to create a file.

In a project where we used React in Drupal, it was necessary to create a file with the service. We used JSON API services. You can use the code below to create a file.

axios.post("/jsonapi/media/"+ mediaType +"/"+ mediaField, blob, 
{ 
   "withCredentials": true, 
   "headers": { 
      'Content-Type': 'application/octet-stream', 
      'Accept': 'application/vnd.api+json', 
      'X-CSRF-Token': csrf, 
      'Content-Disposition': 'file; filename="' + filename +'"', 
   } 
}) .then(res => { }); 

The service allows creating files under the files folder of your site. The blob variable that we send as body in our request draws attention. With Drupal services, we can create the file when we send the streamed media we get from another source as a URL by converting it to a blob. We do this as follows:

let blob = await fetch(url).then(r => r.blob()); 

Now that our file is created, we can create the media using the id and type of this file.

axios.post('/jsonapi/media/' + mediaType , 
{ 
   "data": { 
      "type": "media--"+mediaType, 
      "attributes": { 
         "name": label, 
         "field_***": fieldInfo, //If there is other fields. 
      }, 
      "relationships": { 
         "bundle": { 
            "data": bundleData 
         }, 
         [mediaField]: { 
            // Field name differs according to media types. Ex: field_media_image for images 
            "data": { 
               "type": res?.data?.data?.type, //File type 
               "id": res?.data?.data?.id, //File id 
            } 
         } 
      } 
   } 
}, 
{ 
   "withCredentials": true, 
   "headers": { 
      'Content-Type': 'application/vnd.api+json', 
      'Accept': 'application/vnd.api+json', 
      'X-CSRF-Token': csrf, 
   } 
}) .then(response => { });