cloudonix
v1.0.3
Published
Official Cloudonix Upload SDK to upload media files and images.
Downloads
574
Maintainers
Readme
🚀 Cloudonix Upload SDK
Official Node.js and Browser SDK for uploading media files (images, videos, PDFs) to the Cloudonix storage server. Supports both modern ES Modules (import) and legacy CommonJS (require) styles.
[!IMPORTANT]
- 🌐 Official Website: https://cloudonix.shivam-75.workers.dev/dashboard
- 🌐 Official Doc Website: https://shivam-75.github.io/Cloudonix-doc
- 📦 Official Package (NPM): https://www.npmjs.com/package/cloudonix
- 📁 GitHub Repository: https://github.com/Shivam-75/Cloudonix-doc
Refer to the links above for complete integration guides, API keys, dashboard settings, and detailed API references.
✨ Features
- 📦 Zero External Sub-Dependencies: Ultra lightweight, modern codebase.
- 🔄 Universal Support: Works seamlessly out of the box with ES Modules (ESM) and CommonJS (CJS).
- ⚡ Modern Standards: Built on native Web APIs (
fetchandFormData). - 🛡️ Fail-safe Error Handling: Structured JSON responses with try-catch compatibility.
- 📂 Multi-file Support: Upload images, videos, documents/PDFs, and more.
🛠️ Step-by-Step Installation & Setup
Follow these simple steps to integrate Cloudonix into your Node.js application.
Step 1: Install the SDK
Install the package using your favorite package manager:
npm install cloudonixStep 2: Get Your API Key
- Visit the Cloudonix Documentation & Dashboard.
- Create an account or log in to get your custom API Key (e.g.,
cx_154a6d1...).
Step 3: Choose Your Implementation Style
Implement the code using one of the three examples below based on your tech stack.
💻 Code Examples
1. Modern ES Modules (ESM)
Use this style if your package.json contains "type": "module":
import Cloudonix from 'cloudonix';
import fs from 'node:fs';
// 1. Initialize the SDK
const uploader = new Cloudonix({
api_key: 'YOUR_CLOUDONIX_API_KEY'
});
try {
// 2. Read file to buffer & convert to native File/Blob
const buffer = fs.readFileSync('./my-image.png');
const file = new File([buffer], 'my-image.png', { type: 'image/png' });
console.log('Uploading image...');
// 3. Upload file using try-catch safety
const response = await uploader.upload(file);
if (response.success) {
console.log('Successfully uploaded! URL:', response.data.imageUrl);
} else {
console.error('Upload rejected by server:', response.error);
}
} catch (error) {
console.error('Network or client-side error occurred:', error.message);
}2. Legacy CommonJS (CJS)
Use this style if you are importing modules using require:
const Cloudonix = require('cloudonix');
const fs = require('node:fs');
// 1. Initialize the SDK
const uploader = new Cloudonix({
api_key: 'YOUR_CLOUDONIX_API_KEY'
});
async function runUpload() {
try {
// 2. Read file to buffer & convert to Blob/File
const buffer = fs.readFileSync('./my-document.pdf');
const file = new File([buffer], 'my-document.pdf', { type: 'application/pdf' });
console.log('Uploading PDF document...');
// 3. Upload file
const response = await uploader.upload(file);
if (response.success) {
console.log('Successfully uploaded! URL:', response.data.pdfUrl);
} else {
console.error('Upload rejected:', response.error);
}
} catch (error) {
console.error('Unexpected error:', error.message);
}
}
runUpload();3. Express.js API Route (with Multer Uploads)
Standard setup to allow users of your website to upload images/videos/PDFs directly to Cloudonix:
First, install the backend web dependencies:
npm install express multerThen create your Express server:
import express from 'express';
import multer from 'multer';
import Cloudonix from 'cloudonix';
import fs from 'node:fs';
import path from 'node:path';
const app = express();
const port = 3000;
// Configure multer to save files on disk
const storage = multer.diskStorage({
destination: (req, file, cb) => {
const uploadDir = './uploads';
// Ensure the upload directory exists
if (!fs.existsSync(uploadDir)) {
fs.mkdirSync(uploadDir, { recursive: true });
}
cb(null, uploadDir);
},
filename: (req, file, cb) => {
// Generate a unique filename using timestamp and random number
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
cb(null, file.fieldname + '-' + uniqueSuffix + path.extname(file.originalname));
}
});
const upload = multer({ storage: storage });
// Initialize the Cloudonix SDK
const uploader = new Cloudonix({
api_key: 'YOUR_CLOUDONIX_API_KEY'
});
// Route to handle file uploads (supports image, video, pdf, etc.)
app.post('/upload', upload.single('file'), async (req, res) => {
try {
// 1. Validate if a file is present in the request
if (!req.file) {
return res.status(400).json({
success: false,
error: 'No file was provided.'
});
}
// 2. Read the uploaded file from disk and convert to Blob
const buffer = fs.readFileSync(req.file.path);
const file = new Blob([buffer], { type: req.file.mimetype });
console.log(`Uploading file ${req.file.originalname} of type ${req.file.mimetype} to Cloudonix...`);
// 3. Upload file to Cloudonix
const response = await uploader.upload(file);
if (response.success) {
res.status(200).json({
success: true,
message: 'Uploaded successfully!',
data: response.data
});
} else {
res.status(500).json({
success: false,
error: response.error
});
}
} catch (error) {
// Catch any unexpected exceptions during the request processing or upload
console.error('Upload handler error:', error);
res.status(500).json({
success: false,
error: 'An unexpected internal error occurred: ' + error.message
});
} finally {
// 4. Always clean up the temporary file from the disk after upload/error
if (req.file && req.file.path && fs.existsSync(req.file.path)) {
try {
fs.unlinkSync(req.file.path);
} catch (cleanupError) {
console.error('Error deleting temporary file:', cleanupError);
}
}
}
});
app.listen(port, () => {
console.log(`Server is running at http://localhost:${port}`);
});📖 API Reference
new Cloudonix(config)
Initializes a new Cloudonix client instance.
| Parameter | Type | Required | Description |
| :--- | :--- | :--- | :--- |
| config | Object | Yes | Configuration settings. |
| config.api_key | String | Yes | Your secret API key from the Cloudonix console. |
uploader.upload(file)
Uploads a standard File or Blob object to the Cloudonix server.
file(File/Blob): A browser-standardFileorBlobobject (Required).- Returns (Promise):
success(Boolean):trueif the upload succeeded,falseotherwise.data(Object): Response payload from the server:imageUrl(String): URL of the uploaded image (for image uploads).pdfUrl(String): URL of the uploaded PDF (for PDF uploads).videoUrl(String): URL of the uploaded video (for video uploads).
error(String): Description of the error ifsuccessisfalse.
📄 License
MIT License. See LICENSE for details.
