UNPKG

cloudku-uploader

Version:

Modern zero-dependency file uploader with auto-conversion, chunked uploads, and TypeScript support. Upload images, videos, audio, and documents to CloudKu with blazing-fast performance.

93 lines (82 loc) 3.79 kB
class UploadFile { constructor() { this.baseUrls = [ 'https://cloudkuimages.guru', 'https://cloudkuimages-guru.us.itpanel.app' ]; this.headers = { 'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'x-xss-protection': '0', 'referrer-policy': 'strict-origin-when-cross-origin,origin', 'x-provided-by': 'StackCDN', 'Referer': 'https://cloudkuimages.guru', 'Origin': 'https://cloudkuimages.guru', 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36' }; this.currentUrlIndex = 0; } buildFormData(fileBuffer, fileName, expireDate = null) { const boundary = '----formdata-' + Math.random().toString(36); let body = `--${boundary}\r\n`; body += `Content-Disposition: form-data; name="file"; filename="${fileName}"\r\n`; body += `Content-Type: application/octet-stream\r\n\r\n`; const encoder = new TextEncoder(); const bodyStart = encoder.encode(body); let expireSection = new Uint8Array(0); if (expireDate) { const expireBody = `\r\n--${boundary}\r\n`; const expireField = `Content-Disposition: form-data; name="expire_date"\r\n\r\n${expireDate}`; expireSection = encoder.encode(expireBody + expireField); } const bodyEnd = encoder.encode(`\r\n--${boundary}--\r\n`); const totalLength = bodyStart.length + fileBuffer.length + expireSection.length + bodyEnd.length; const fullBody = new Uint8Array(totalLength); let offset = 0; fullBody.set(bodyStart, offset); offset += bodyStart.length; fullBody.set(new Uint8Array(fileBuffer), offset); offset += fileBuffer.length; fullBody.set(expireSection, offset); offset += expireSection.length; fullBody.set(bodyEnd, offset); return { fullBody, boundary }; } upload(fileBuffer, fileName = 'upload.jpg', expireDate = null) { return new Promise((resolve) => { this.currentUrlIndex = 0; const endpoint = expireDate ? '/temp.php' : '/upload.php'; const tryUpload = () => { const url = this.baseUrls[this.currentUrlIndex] + endpoint; const { fullBody, boundary } = this.buildFormData(fileBuffer, fileName, expireDate); fetch(url, { method: 'POST', headers: { ...this.headers, 'Content-Type': `multipart/form-data; boundary=${boundary}` }, body: fullBody }) .then(response => response.json()) .then(result => { result.information = 'https://cloudkuimages.guru/ch'; resolve(result); }) .catch(err => { this.currentUrlIndex++; if (this.currentUrlIndex < this.baseUrls.length) { tryUpload(); } else { resolve({ status: 'error', message: 'Upload failed: ' + err.message, information: 'https://cloudkuimages.guru/ch' }); } }); }; tryUpload(); }); } } module.exports = UploadFile;