Getting Started with CldUploadWidget

The CldUploadWidget creates a new instance of the Cloudinary Upload Widget giving you an easy way to add upload capabilities to your Svelte app.

Basic Usage

The CldUploadWidget will not render any UI by default. It will instead only render what’s returned from the child function (see more below).

There are two options when using the CldUploadWidget: signed and unsigned. These options allow you to control the amount of security and restrictions you place on uploads.

To learn more about signed and unsigned upload, check out the Cloudinary docs

Unsigned

To give unsigned access for upload, provide an upload preset as part of the component configuration.

Note: The upload preset requires that unsigned uploads are permitted.

Use the following to generate an unsigned upload widget:

<script>
	import { CldUploadWidget } from 'svelte-cloudinary';
</script>

<CldUploadWidget uploadPreset="<Upload Preset>" let:open let:isLoading>
	<button className="button" on:click={open} disabled={isLoading}> Upload an Image </button>
</CldUploadWidget>

URL: Upload to see example result.

Signed

Signing upload requests requires passing in an endpoint to the component.

You can do this by creating a serverless function that reads the parameters as the body and returns an object with the signature.

Use the following to generate an signed upload widget:

<script>
	import { CldUploadWidget } from 'svelte-cloudinary';
</script>

<CldUploadWidget
	uploadPreset="<Upload Preset>"
	let:open
	let:isLoading
	signatureEndpoint="<API Endpoint (ex: /api/sign-cloudinary-params)>"
>
	<button className="button" on:click={open} disabled={isLoading}> Upload an Image </button>
</CldUploadWidget>

Here’s an example of how you could process the signature in an API endpoint that signs a request using SvelteKit:

import { v2 as cloudinary } from 'cloudinary';
import type { RequestHandler } from './$types';
import { env } from '$env/dynamic/private';
import { error, json } from '@sveltejs/kit';

export const POST = (async ({ request }) => {
	const body = await request.json();
	const { paramsToSign } = body;

	try {
		const signature = cloudinary.utils.api_sign_request(paramsToSign, env.CLOUDINARY_API_SECRET);
		return json({ signature });
	} catch (e) {
		return error(500, e.message);
	}
}) satisfies RequestHandler;

To use the above, create a Node-based API route, add the snippet, and use that endpoint as the signatureEndpoint prop.

See a full example of an API endpoint used with the Svelte Cloudinary docs: https://github.com/cloudinary-community/svelte-cloudinary/blob/main/docs/src/routes/api/sign-cloudinary-params/+server.ts

URL: undefined

Watch & Learn

View on YouTube

Learn More about CldUploadWidget


MIT 2023 ©