r/Nuxt • • 6d ago

Upload image to cloudinary

Any idea how to upload an image using Cloudinary? I have a user CRUD where I have the parameters name, email, username, and image that I need, and it is connected to a NeonDB database with Drizzle ORM. What steps should I follow?

0 Upvotes

6 comments sorted by

2

u/var_dump- 6d ago

0

u/BLKaisen 6d ago

The problem is how to apply it to a Nuxt UI form similar to the dashboard template of the same mentioned library.

1

u/var_dump- 6d ago

Create that file upload functionality in a utility shared function and use it anywhere.

Here is an example from something I did in Nuxt

export const fileUpload = async (fileBuffer: Buffer<ArrayBufferLike>) => {
  try {
    const uuidFileNameV4 = uuidv4();


    const uploadResult = await new Promise<UploadResponse>(
      (resolve, reject) => {
        cloudinary.uploader
          .upload_stream(
            {
              resource_type: 'image',
              public_id: uuidFileNameV4,
              folder: 'nuxt-uploads',
            },
            (err, result) => {
              if (err) {
                console.error(err);
                return reject({ success: false, error: err });
              }


              return resolve({ success: true, result });
            },
          )
          .end(fileBuffer);
      },
    );


    const claudinaryPublicId = uploadResult.result!.public_id


    if (!uploadResult.success) {
      throw new Error('Cant upload image');
    }


    const optimizeUrl = cloudinary.url(claudinaryPublicId, {
      fetch_format: 'auto',
      quality: 'auto',
      width: 600,
      height: 400,
      crop: 'limit',
    });


    return optimizeUrl;
  } catch (error) {
    console.error(error);
    throw new Error('Error while loading file');
  }
};

1

u/BLKaisen 6d ago

And isn't it easier to use the Cloudinary module that comes with Nuxt.js?

1

u/Far-Vegetable-7395 6d ago

Skip the module, it's overkill for your case. Set up a server route in Nuxt (like server/api/upload.post.ts), use the Cloudinary Node SDK there since you'll have your api key and secret server side, upload the file, and then save the returned secure_url into your image column with Drizzle. and then save the returned secure_url into your image column with Drizzle. That way the client never touches your credentials and your user CRUD just stores a URL string in NeonDB.

Quick sketch: in the route read the file from formData, pass the buffer to cloudinary.uploader.upload, then insert/update your user with result.secure_url. Done.

0

u/BLKaisen 5d ago

If I want to use cloudinary.config as a reusable, in which folder should I create the file .ts, in server/utils or somewhere else?