How to upload asset to a folder through API call

Hello everyone,

How do I upload a file through api call? I do not find any such mention for v2. Please help.

Hi!

I found the solution myself, as it turned out, everything is very simple :slight_smile:

go to root → modules → Assets → api.php
at the end of the file add:

$restApi->addEndPoint('/assets/upload', [

      'POST' => function($params, $app) {

          $meta = ['folder' => $this->param('folder', '')];

          return $this->module('assets')->upload('files', $meta);
      }
  ]);

The request looks like a regular REST API:

folder is specified only if required

To remove, add the following code:

$restApi->addEndPoint('/assets/remove', [

        'POST' => function($params, $app) {

            if ($assets = $this->param('assets', false)) {
                return $this->module('assets')->remove($assets);
            }
    
            return false;
        }
    ]);

The request looks like a regular REST API:

assets is the id of the image to be removed

It’s probably best to not change core files, because those will be gone when you update Cockpit to a newer version.

Instead, create a file config/api/assets/upload.php and put the code you wrote in there. It may need some alteration to make it work from there though.

I’m not a guru at all, I’ve only learned about these things recently: Get list of unpublished items through API - #8 by witsec.

thanks a lot zhan.dev

you’re right!
then create two files in a folder: root → config → api → assets

upload.php:

<?php
$meta = ['folder' => $this->param('folder', '')];
return $this->module('assets')->upload('files', $meta);

remove.php:

<?php
if ($assets = $this->param('assets', false)) {
    return $this->module('assets')->remove($assets);
}
return false;