Change image size and access to the url on SvelteKit

Javier
Javier Member Posts: 2
edited August 2023 in Developer APIs

I am uploading images to Cloudinary from a SvelteKit API with the following code:

My questions are:

1 - How to change the image size, choose a folder, and format of the image.

2 - How to return the URL in the response, so I can display the image to the user.

3 - If there are better ways to to upload imgs, I’ll be thankful to know them.

export const POST = async ({request}) => {

const formData = await request.formData()

const file = formData.get('file')

const arrayBuffer = await file.arrayBuffer();

const buffer = Buffer.from(arrayBuffer) //  <-- convert to Buffer

    const onDone = (error, result) => {

        if (error) {
            return { success: false, error }
        }
        return { success: true, result }
    }

      const {url } = await cloudinary.uploader.upload_stream({ resource_type: "image" }, onDone).end(buffer)

    return new Response( JSON.stringify({msg: 'IMg uploaded'}))

}
Tagged:

Best Answer

Answers

  • sanjaysarathy
    sanjaysarathy Member, Cloudinary Staff Posts: 4

    For a Svelte-specific resource, you may want to check out the Svelte Community Library which was released last month. https://svelte.cloudinary.dev/

  • Javier
    Javier Member Posts: 2
    edited August 2023

    But I don’t see any options in the library to upload imgs from your app to Cloudinary, just some components to deliver the imgs you already have in Cloudinary. Am I missing something?

  • matiasfh
    matiasfh Member Posts: 1

    Hi @Javier , You are right. The svelte-cloudinary library was first released with only support for the CldImage and CldOgImage components to display images hosted in Cloudinary and to use the full power of Cloudinary transformations.

    But just today, we released a new version of it with support for three new components:

    • CldUploadWidget: A way to tap into the Cloudinary Upload Widget to allow users to upload images
    • CldUploadButton: A thin wrapper on top of CldUploadWidget to display a customizable button to allow users to upload widget
    • CldVideoPlayer: A simple way to play a video hosted on Cloudinary and use any transformation you need.

    Please take a look at https://svelte.cloudinary.dev for the updated documentation.

    Now, if you don't want to use the Cloudinary widget https://cloudinary.com/documentation/upload_widget then you'll need to upload images from the +page.server.js or +server.js files within your SvelteKit app by using the upload_stream API, as you mentioned in your first post, and then apply the transformations on the image when consuming it. You can do this with CldImage from the svelte-cloudinary library or by hand using the URL of the URL-GEN SDK.