Search code examples
next.jsnext.js13cloudinary

cloudinary upload api: How to set quality? Next.js / react


This is my code. I tried adding .../upload/q_70 or .../upload/q_70/ But as soon as i do this i get an 404 error and some cross origin errors. Its hard to reproduce the errors now again. But maybe i am completely on the wrong path.

const handleUploadMultipleImagesInput = async (images) => {
    if (!imageChanged.otherImages) {
      return form.images.other;
    }
    if (isEmptyArray(images)) {
      const resetOtherImagesToDefault = [{ publicID: '', resourceType: '', type: '' }];
      return resetOtherImagesToDefault;
    }
    const preset = 'cy1wyxej';
    const url = 'https://api.cloudinary.com/v1_1/drt9lfnfg/image/upload';

    let otherImagesIndexObject = [];
    for (let image of images) {
      if (image?.publicID) {
        const otherImagesImageResObject = { ...image };
        otherImagesIndexObject.push(otherImagesImageResObject);
      } else {
        const formData = new FormData();
        formData.append('file', image.file);
        formData.append('upload_preset', preset);
        formData.append('quality', '10');
        const uploadRes = await fetch(url, {
          method: 'POST',
          body: formData,
        });
        console.log('uploadRes', uploadRes);
        const data = await uploadRes.json();
        console.log('data', data);
        const otherImagesImageResObject = {
          publicID: data.public_id,
          resourceType: data.resource_type,
          type: data.type,
          id: image.id,
        };
        otherImagesIndexObject.push(otherImagesImageResObject);
      }
    }
    return otherImagesIndexObject;
  };

Solution

  • It is almost always you would want to upload the image's full resolution then only transform the image on delivery e.g. using the q_10 in the URL, check this reference: https://cloudinary.com/documentation/transformation_reference#q_auto.

    Here a sample image with q_70 transformation: https://res.cloudinary.com/demo/q_70/sample

    In any case, the other option is to configure your upload preset in the settings page. Pick/edit the upload preset > Upload Manipulation > Add Eager. Set the Quality parameter slider to 10, then save your changes. From this point on, every time you use this upload preset, Cloudinary will generate a derive of your image based on the eager transformation: q_10. Thus, you won't need to append formData.append('quality', '10'); in the form submission.