Uploading Images

The default image upload method just creates a dummy URL to show how you can create your file object.

const {
  BaseKit,
  Image,
  // Video,
  // Table
} = this.$extensions;

Image.configure({
  upload(file) {
    const url = URL.createObjectURL(file)
    console.log('mock upload api :>> ', url) //  blob:http://192.168.231.130:3000/c25b49c6-8feb-4db6-bf00-593a8351eaab
    return Promise.resolve(url) 
  }
}),

Uploading Your Image to Server

The example below shows how to encode your file to base64 for easy file transfer and how to upload the encoded file to the server using async function.

Important

Your image upload function should return the URL address that will be displayed in the browser after the image is uploaded, as in the example below. Thus, the Image extension receives the display address of the url image and passes it to the editor.

import axios from 'axios';
/**
 * Convert file to base64 encoded object
 */
export const toBase64 = file => new Promise((resolve, reject) => {
  const reader = new FileReader();
  reader.readAsDataURL(file);
  reader.onload = () => resolve(reader.result);
  reader.onerror = reject;
});
/**
 * Generate uuid
 */
export const generateUid = function(uppercase = false) {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
    var r = (Math.random() * 16) | 0,
      v = c == "x" ? r : (r & 0x3) | 0x8;
    let uuid = v.toString(16);
    return (uppercase) ? uuid.toUpperCase() : uuid;
  });
}

Image.configure({
    async upload(file) {
      const base64 = await toBase64(file);
      let url = null;
      try {
        const fileId = generateUid();
        const res = await axios.post('/create-file.php', {
          fileId: fileId, // create random file id
          fileName: file.name,
          fileType: file.type,
          fileSize: (file.size / 1024).toFixed(2),
          fileData: base64,
        });

        if (res?.status === 200) {
          url = `http://example.local/read-file.php?fileId=${fileId}`
        }
      } catch (error) {
        console.error('File upload error:', error);
      }
      return url;
    }
})

Server Side

create-file.php

<?php
header("Content-Type: application/json");
http_response_code(200);

$data = json_decode(file_get_contents("php://input"), true);

if (!$data || !isset($data["fileId"], $data["fileName"], $data["fileType"], $data["fileData"])) {
    http_response_code(400);
  echo json_encode(["error" => "Invalid input"]);
  exit;
}
$fileId = $data["fileId"];
$fileName = basename($data["fileName"]);
$fileType = $data["fileType"];
$fileData = $data["fileData"];

$uploadDir = __DIR__ . "/uploads";
if (!is_dir($uploadDir)) {
  mkdir($uploadDir, 0777, true);
}
$filePath = "$uploadDir/$fileId-" . $fileName;
$fileContent = base64_decode(preg_replace('#^data:image/\w+;base64,#i', '', $fileData));

if (file_put_contents($filePath, $fileContent) !== false) {
  echo json_encode(["message" => "File uploaded successfully"]);
} else {
    http_response_code(500);
  echo json_encode(["error" => "Failed to save file"]);
}

read-file.php

<?php
if (!isset($_GET["fileId"])) {
    http_response_code(400);
    echo "Missing fileId";
    exit;
}
$fileId = preg_replace("/[^a-zA-Z0-9_-]/", "", $_GET["fileId"]);
$uploadDir = __DIR__ . "/uploads";

$files = glob("$uploadDir/$fileId-*");
if (!$files) {
    http_response_code(404);
    echo "File not found";
    exit;
}
$filePath = $files[0];
$fileInfo = pathinfo($filePath);
$fileMime = mime_content_type($filePath);

http_response_code(200);
header("Content-Type: $fileMime");
header("Content-Length: " . filesize($filePath));
readfile($filePath);