UNPKG

payload-cloudinary

Version:
75 lines 3.08 kB
'use client'; import { createClientUploadHandler } from '@payloadcms/plugin-cloud-storage/client'; /** * Creates a client upload handler for Cloudinary * * This handler enables direct client-side uploads to Cloudinary, * bypassing your server for the actual file upload while still * maintaining security through signed upload requests. * * @example * ```ts * // In your client-side code * import { CloudinaryClientUploadHandler } from 'payload-cloudinary/client' * * export const uploadHandler = CloudinaryClientUploadHandler * ``` */ export const CloudinaryClientUploadHandler = createClientUploadHandler({ handler: async ({ apiRoute, collectionSlug, file, serverHandlerPath, serverURL }) => { // Step 1: Request signature from server const signatureResponse = await fetch(`${serverURL}${apiRoute}${serverHandlerPath}`, { body: JSON.stringify({ collectionSlug, filename: file.name, }), credentials: 'include', headers: { 'Content-Type': 'application/json', }, method: 'POST', }); if (!signatureResponse.ok) { throw new Error(`Failed to get upload signature: ${signatureResponse.statusText}`); } const signatureData = (await signatureResponse.json()); // Step 2: Upload directly to Cloudinary using the signature const formData = new FormData(); formData.append('file', file); formData.append('api_key', signatureData.api_key); formData.append('timestamp', signatureData.timestamp.toString()); formData.append('signature', signatureData.signature); formData.append('public_id', signatureData.public_id); // Add all upload options from the server Object.entries(signatureData.upload_options).forEach(([key, value]) => { // Skip parameters that are already added or that shouldn't be in FormData if (key === 'api_key' || key === 'timestamp' || key === 'signature' || key === 'public_id' || key === 'file') { return; } // Handle different value types if (typeof value === 'object' && value !== null) { formData.append(key, JSON.stringify(value)); } else if (value !== undefined && value !== null) { formData.append(key, String(value)); } }); // Upload to Cloudinary const uploadResponse = await fetch(signatureData.upload_url, { body: formData, method: 'POST', }); if (!uploadResponse.ok) { const errorText = await uploadResponse.text(); throw new Error(`Cloudinary upload failed: ${errorText}`); } const result = await uploadResponse.json(); // Return empty object as required by the handler interface return {}; }, }); //# sourceMappingURL=CloudinaryClientUploadHandler.js.map