File/asset upload trough the API

I think you don’t have to do it after you uploaded the file, it returns the whole path of the file. So, you’ll only have to add a new field like file_link to attach your new entry.

You are in the wrong HEADER format. As you’re sending file, you don’t have to add “Content-Type: application/json”

I also had the same issue before, actually it should be files[], instead of files[0].

This below example work 100%. Hope it helps you.

Upload via Javascript (AJAX)

HTML

<input type="file" name="myFile" id="myFile">
      <button class="upload">Upload</button><br>
<img class="preview-img">

Javascript


const API_URL = '';
const TOKEN   = '';

function uploadImage(){
  
            const PATH      = '/api/cockpit/addAssets?token=';
            const api       = API+PATH+TOKEN;
            const fileInput = document.querySelector('input[type="file"]');
            const formData  = new FormData();
  
            formData.append('files[]', fileInput.files[0]);
  
          
            fetch(url,{
                method : 'POST',
                body : formData
            })
            .then(e=>e.json())
            .then(res=>{
                const {assets} = res;
                if(!assets){
                    alert('Upload failed!');
                    return;
                }
              
               const image_url = API_URL+'/storage/uploads'+assets[0].path;
              
               document.querySelector(".preview-img").src= image_url;
              
               alert('Successfully uploaded!');

            })
}

document.querySelector(".upload").addEventListener('click',()=>{
   uploadImage()
})


Upload via PHP ( CURL )

PHP

<?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 $result;
};

$API   = 'https://your_cockpit_api.com';
$TOKEN = '80b0e4625d1e7ff753f1d45967a92f';
$FILE  = 'file.txt';
$data  = uploadImage($API,$TOKEN,$FILE);
echo $data;