Score:0

How to remove an uploaded file with JSON:API?

cn flag

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?

Score:1
br flag

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.

Score:0
cn flag

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.

I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.