1

I'm using vite-react frontend with express back end. I'm trying to resize an image using sharp and then upload it to Cloudinary. So far no matter what I try the image never resizes and is always the same size as the original. I'm sending the image via API to the backend. This is my photo.routes.js file contents

const express = require("express");
const router = express.Router();
const { upload } = require("../config/cloudinary.config");
const sharp = require("sharp");

router.post("/", upload.single("photo"), async (req, res) => {
    try {
        const result = req.file;

        const buffer = result.buffer;

        const resizedImageBuffer = await sharp(buffer)
            .resize({
                width: 150,
                height: 150,
                fit: sharp.fit.inside,
                withoutEnlargement: true,
            })
            .toBuffer();
    
const response = await cloudinary.v2.uploader.upload_stream({
    resource_type: 'image',
    folder: "user_profiles",
    public_id: result.originalname,
    overwrite: true,
}, (error, result) => {
    if (error) {
        console.log('Error uploading resized image:', error);
        res.status(500).json({
            message: "Error uploading resized image",
            error,
        });
    } else {
        res.status(200).json({
            message: "Photo uploaded and resized successfully",
            result,
        });
    }
}).end(resizedImageBuffer);


        res.status(200).json({
            message: "Photo uploaded and resized successfully",
            result,
        });
    } catch (error) {
        console.log(error.message); 
        console.log(error.stack); 
        res.status(500).json({
            message: "Error uploading and resizing the photo",
            error,
        });
    }
});
module.exports = router;

I'm not getting any errors in the server console. The photo appears in the correct folder in cloudinary. The link to the file saves in my Firebase and displays on my webpage. I've been trying this for the past 2 days. Any help would be greatly appreciated.

JohnM
  • 71
  • 7
  • 1
    You could check whether the image is really converted by `sharp` to the expected dimension by using the `toFile()`. Additionally, you may refer to some examples of using the [Cloudinary SDK upload here](https://github.com/cloudinary/cloudinary_npm/blob/518c0e5a0e07f4a39ae730e28a4436a5e348217d/samples/basic/basic.js). – epasos_573 Apr 13 '23 at 06:16
  • 1
    @epasos_573 - Thank you for responding :-) I took a different approach by resizing in react utilising react-image-file-resizer and then uploading via my express backend. Works exactly how I need it now. – JohnM Apr 13 '23 at 10:14

1 Answers1

0

The error in the code is in the following line:

const response = await cloudinary.v2.uploader.upload_stream({

The cloudinary variable is not defined in this code. To fix this, you need to import the cloudinary module and initialize it with your Cloudinary credentials before using it in this code.

Here's the fixed code with the cloudinary module imported and initialized:

const express = require("express");
const router = express.Router();
const { upload } = require("../config/cloudinary.config");
const sharp = require("sharp");
const cloudinary = require("cloudinary").v2;

// Initialize Cloudinary credentials
cloudinary.config({
  cloud_name: "your_cloud_name",
  api_key: "your_api_key",
  api_secret: "your_api_secret",
});

router.post("/", upload.single("photo"), async (req, res) => {
  try {
    const result = req.file;

    const buffer = result.buffer;

    const resizedImageBuffer = await sharp(buffer)
      .resize({
        width: 150,
        height: 150,
        fit: sharp.fit.inside,
        withoutEnlargement: true,
      })
      .toBuffer();

    // Upload the resized image to Cloudinary
    cloudinary.uploader.upload_stream(
      {
        resource_type: "image",
        folder: "user_profiles",
        public_id: result.originalname,
        overwrite: true,
      },
      (error, result) => {
        if (error) {
          console.log("Error uploading resized image:", error);
          res.status(500).json({
            message: "Error uploading resized image",
            error,
          });
        } else {
          res.status(200).json({
            message: "Photo uploaded and resized successfully",
            result,
          });
        }
      }
    ).end(resizedImageBuffer);
  } catch (error) {
    console.log(error.message);
    console.log(error.stack);
    res.status(500).json({
      message: "Error uploading and resizing the photo",
      error,
    });
  }
});

module.exports = router;

Note that you still need to replace your_cloud_name, your_api_key, and your_api_secret with your own Cloudinary credentials.

Sohail Pathan
  • 308
  • 2
  • 8
  • thank you for your reply. It was being called in via const { upload } = require("../config/cloudinary.config"); however, I had changed the code so many times it was accidentally left out when uploading the question. The actual import statement was with the orginal code but the error was still there. – JohnM Apr 18 '23 at 13:54