$234
a new file upload
Updated 6 months ago
import { v2 as cloudinary } from 'cloudinary'; cloudinary.config({ cloud_name: process.env.NEXT_PUBLIC_CLOUDINARY_CLOUD_NAME, api_key: process.env.CLOUDINARY_API_KEY, api_secret: process.env.CLOUDINARY_API_SECRET, secure: true, }); export const uploadImageToCloudinary = async ( buffer: Buffer, path: string, onProgress: (percentage: number) => void ): Promise<any> => { return new Promise((resolve, reject) => { const url = `https://api.cloudinary.com/v1_1/${cloudinary.config().cloud_name}/upload`; const xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.upload.onprogress = (event) => { if (event.lengthComputable) { const percentComplete = (event.loaded / event.total) * 100; onProgress(percentComplete); } }; xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(JSON.parse(xhr.responseText)); } else { reject(new Error(xhr.statusText)); } }; xhr.onerror = () => reject(new Error('Upload failed'));