Created
November 25, 2020 15:19
-
-
Save ronaldaug/5a8707e74e7f24e8df73629af8749d58 to your computer and use it in GitHub Desktop.
Revisions
-
ronaldaug created this gist
Nov 25, 2020 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,99 @@ <details> <summary>Upload via Javascript (AJAX)</summary> **HTML** ```html <input type="file" name="myFile" id="myFile"> <button class="upload">Upload</button><br> <img class="preview-img"> ``` **Javascript** ```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 image 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() }) ``` </details> ------- <details> <summary>Upload via PHP ( CURL )</summary> **PHP** ```php <?php function uploadImage($api,$token,$file){ $path = '/backend/api/cockpit/addAssets?token='; $url = $api.$path.$token; $fname = $file; $cfile = new CURLFile(realpath($fname)); $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; ``` </details>