Deleting unused user files

Hi all,
I have an upload button on my site which allows users to upload up to 6 images and another for documents. The issue I’m having is that users will often upload some images and then replace them with something else, causing unnecessary space to be taken up in the media manager. Does anyone know of a way to automatically remove files which cannot be found in any collections/datasets? I imagine my two options are to either periodically check to make sure there are no unnecessary files every week or so, or to run a check every time a form is updated. Though for both options I’m not quite sure where to even start.
I would much appreciate some help and guidance.
Thanks.

Thank you for giving this knowledge in this post, which is nice https://mybkexperience.site/

You can’t delete media files through Velo code, but you can move them into the trash bin.
You can do something like this:
in backend data.js file create an afterUpdate hood.
In this hook compare the files in the item images field to the current item images (which represents the item prior to the update).
If there are images in the previous item that does no longer exist in the new item, move it to trash with mediaManager.moveFilesToTrash(fileUrls).
See:
https://www.wix.com/velo/reference/wix-data/hooks/afterupdate

https://www.wix.com/velo/reference/wix-media-backend/mediamanager-obj/movefilestotrash

Hi thanks for the suggestion.
I have written something basic for now just to test it out and it seems the getting new and old links just fine. However, I’m having an issue with the formatting of the links. Images which are uploaded through an upload button will be of format Wix:image while images stored in the visitor files section of the media manager will be static.wixStatic. this (I’m assuming is the reason why) is the moveFilesToTrash function to not do anything. Do you know how I might get it working?

You can convert the Wix:image to full URL by doing something like:

const fullURL = `https://static.wixstatic.com/${wixImageLink.split('/')[3]}`;