0

I have an image field on the User entity that saves to the private filesystem. The field is limited to one image.

I can POST an image file to the field using JSON:API in accordance with this change record.

However, I cannot figure out how to delete a posted file. I don't want to upload a new file to replace it; I want to remove the file that was uploaded from the user. How can I do that?

2 Answers 2

1

Do you mean the reference to the field, or the actual file?

In the first case you could just PATCH the relative user, setting the field to empty. However the psychical file will remain on the server. To ensure its deletion you'll have to change the default Drupal behaviour: https://www.drupal.org/node/2891902

Please note in case the user field is a media, you'll need to actually delete the media and not only the reference to it on the user entity.

Otherwise, you could just do a DELETE against the file entity, e.g.

DELETE yoursite.com/sonapi/file/file/ff861ea2-b4ac-459f-9e27-06f8c77e252a

Please note you'll probably need to nevertheless PATCH the user entity and also DELETE the media entity to drop the dead references.

0

As @Giuseppe noted, if you want to delete the file and remove the reference to it from the entity, then you need to PATCH the entity and DELETE the file.

I implemented this by PATCHing the entity in the client and then using hook_ENTITY_TYPE_presave() to detect when the PATCH occurs (when $entity->original has a file reference and $entity does not), and then deleting the file within the presave hook. I think this might prove to be more reliable than trusting the client to do both file DELETE and entity PATCH.

Another issue to watch in this area is the ongoing effort to unify REST, JSON:API, and other file uploads.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.