Skip to main content

Adding an image via RESTUI can be done in a snap... once you know how!  I have spent a good amount of time (days) researching how come my scripts weren't running correctly.

POST:

authentication: basic,

formats: hal_json

URL:
  • Enable File from domain.com/admin/config/services/rest;
  • Download file_entity module and enable it; and
  • Set permission Add and upload new files under file entity.
How to setup your request:

domain.com/entity/file?_format=hal_json

Header:

Authorization: Basic <token>

Content-Type: application/hal+json

Method:

POST

Body:
{"_links":{
"type":{"href": "https://domain.com/rest/type/file/image"}
},
"filename":[{"value":"imagename.jpg"}],
"filemime":[{"value":"image/jpeg"}],
"type": [{"target_id": "image"}],
"data":[{"value":"base64"}]
}

The image data needs to be converted to Base64.

 

Fine tuning
Define the path

If you want to save your image file to a specific directory in the files directory add the following to the body:

"uri": [{"value": "public://directory_path/imagename.jpg"}],

Replace directory_path with the path from the files directory.  For example, if your directory path from the files directory is pictures > general, then directory_path would be pictures/general.  The uri call becomes

"uri": [{"value": "public://pictures/general/imagename.jpg"}],
Define the user.uid

When I saved the image, I checked to see what user.uid was being referenced against the image in the database.  The value was NULL.  Even though the user is being logged in via basic authentication, their uid was not being applied.  To associate a specific user add the following to the body:

"uid": [{"target_id": "#reference_number"}],

Using the line above, replace #reference_number with the user.uid value.  For example, for user.uid 234 the line would become:

"uid": [{"target_id": "234"}],

 

File entity patch

When you post a file using file_entity, it will save the file temporarily only.  However, there is a patch for this... see Files created with REST API are only temporary.  On this link, you will need to add one line of code:

$entity->status = FILE_STATUS_PERMANENT;

Note... the line above is to be added to the FileEntityNormalizer file

modules/file_entity/src/Normalizer/FileEntityNormalizer.php

Related articles

Andrew Fletcher15 Mar 2024
Could not apply patch! Skipping
Attempting to apply a patch in Drupal 10.2.4 that had been working until this version. &nbsp;Now I'm seeing the following errorCould not apply patch! Skipping. The error was: The process "patch '-p1' --no-backup-if-mismatch -d '/Users/andrewfletcher/Sites/codebales/modules/contrib/facets' &lt;...