Upload Asset With API

I have been trying to create a form that will allow an image upload to the assets - used the PHP from here: https://discourse.getcockpit.com/t/file-asset-upload-trough-the-api/1208/6 but I cannot get it to work at all!

I have:


<form method="POST" id="formid" enctype="multipart/form-data">
<input type="file" name="myFile" id="myFile">
      <button class="upload">Upload</button><br>
<img class="preview-img">
    </form>

<?php

function uploadImage($api,$token,$file){

    $url     = 'http://mydomain.com/data/api/cockpit/addAssets?token=xxxxxxxxx';
    $cfile   = new CURLFile(realpath($file));
    $post    = ['files[]' => $cfile];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result  = curl_exec ($ch);

    return $result;
};

?>


This retrurns a null result.

Can anyone point me in the right direction to het this working please!

Thanks

Sorry for late reply, I tested the codes and I can confirmed this works 100%.
I think you might be confused with Ajax and PHP Curl. As I made two accordion toggles, one for AJAX implementation with JS. And another one for PHP Curl.

If you want a full version of uploading via PHP, please try this below code. Make sure both Cockpit API and your php server are https, and no CORS problem.

<?php

function uploadImage($api,$token,$file){

    $path    = '/api/cockpit/addAssets?token=';
    $url     = $api.$path.$token;
    $cfile   = new CURLFile(realpath($file));
    $post    = ['files[]' => $cfile];

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_HTTPHEADER,array('Content-Type: multipart/form-data'));
    curl_setopt($ch, CURLOPT_TIMEOUT, 10000);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $post);

    $result  = curl_exec($ch);

    return json_encode($result);
};

$API   = 'http://mydomain.com';
$TOKEN = 'xxxxxxxxxxxxxxxxxxxxxx';

if($_FILES['myFile']){
    $FILE  = $_FILES['myFile']['tmp_name'];
    $data  = uploadImage($API,$TOKEN,$FILE);
    echo $data;
}

?>

<form method="POST" id="formid" enctype="multipart/form-data">
<input type="file" name="myFile" id="myFile">
      <button class="upload">Upload</button>
</form>