Is there an event that is triggered when a file is uploaded/added

Is there an event that is triggered when a file is uploaded/added?
There are many events for handling user management such as UserAddedEvent and UserRemovedvent but I could not find similar for files & folders.

I think this is the Event you are after

If you want to listen for just file creation and not folders you will need to check that the Node is a file in the listener itself.

Thanks for the quick reply. Can you give an example on usage?

You can write a Listener to the event:

use OCP\EventDispatcher\Event;
use OCP\Files\Events\Node\NodeCreatedEvent;
use OCP\EventDispatcher\IEventListener;

class MyNodeCreatedListener implements IEventListener {
	public function handle(Event $event): void {
		// Sanity check that event listener got called for the relevant event.
		if (!($event instanceof NodeCreatedEvent)) {
			return;
		}

		$node = $event->getTarget();
		// ... now you can do whatever you want with the node ...
		if ($node instanceof \OCP\Files\File::class) {
			// ... node is a file ...
		}
	}
}

Then you need to register the listener, usually this is done in Application::register.

$context->registerEventListener(NodeCreatedEvent::class, MyNodeCreatedListener::class);

Example of a listener registration.

1 Like

Thanks! I’ll try that out.
I also tried using listen:
$user=\OC::$server->getUserSession(); $user->listen('\OC\User', 'postLogin', function($user2) {echo "hello user";}); $user->listen('OC\Files', 'postCopy', function($node) {echo "hello node";});
The listener works for “postLogin” but not “postCopy”. I am not sure if I $user for that is ok.

VSCode is complaining that here is an error at line
if ($node instanceof \OCP\Files\File::class) {
where syntax error, unexpected token “class”, expecting variable or “$”

My mistake, I wrote the code directly on the post editor without checking it, it should be

if ($node instanceof \OCP\Files\File) {

When event is triggered by NodeCreatedEvent or other Node-type event is there a way to determine from the event object what action was involved? for example when listening to BeforeNodeCreatedEvent how can I find out if it was triggered by copying a file or by downloading a file?