0

I was trying to upload an image but my file did't send, I did it with multer and it worked, but now that I am trying with Cloudinary, it doesnt work, Im new using cloudinary so I don't know if the error is related to it or not, or maybe I am using wrong postman hahaha

I try this:

require('dotenv').config(); // Importar configuración de variables de entorno con dotenv
const { Multimedia } = require('../db.js');
const authMiddleware = require('../controllers/authMiddleware.js');
const { Router } = require('express');
const router = Router();
const cloudinary = require('cloudinary').v2;

// Configuración de Cloudinary
cloudinary.config({
  cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
  api_key: process.env.CLOUDINARY_API_KEY,
  api_secret: process.env.CLOUDINARY_API_SECRET
});

router.post('/', authMiddleware, async (req, res) => {
  
  try {
    const { type } = req.body;
    const file = req.file;

    if (!file) {
      return res
        .status(400)
        .json({ message: 'you didnt send any file' });
    }
    if (type !== 'photo' && type !== 'video') {
      return res
        .status(400)
        .json({ message: 'the file is good!' });
    }

    const result = await cloudinary.uploader.upload(file.tempFilePath, {
      resource_type: type === 'photo' ? 'image' : 'video'
    });
    console.log(result);
    const multimedia = await Multimedia.create({
      type: req.body.type,
      url: result.secure_url,
      user_id: req.user.id
    });

    res.json({
      message: 'you just uploaded a new pic!',
      multimedia
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ message: `server error: ${error.message}` });
  }
});

module.exports = router;

This is what happened when I tried it in Postman:

asportnoy
  • 2,218
  • 2
  • 17
  • 31
  • Please share exact errors you have – pierpy Apr 07 '23 at 04:34
  • first was this error: Cannot read properties of undefined (reading 'file') then I changed : const file = req.files.file to const file = req.file; and got me the .json({ message: 'you didnt send any file' }); – Another Programmer Apr 07 '23 at 04:46
  • 1
    The returned error shows that the execution of your code did not reach the part `const result = await cloudinary.uploader.upload()`. You may check out this [documentation for file uploading in NodeJS](https://www.geeksforgeeks.org/file-uploading-in-node-js/). Additionally, you may refer to this code for using [Multer when uploading file to Cloudinary](https://andela.com/insights/how-to-use-cloudinary-and-nodejs-to-upload-multiple-images/) and [this link as well](https://www.codementor.io/@joejackson045/uploading-images-to-cloudinary-using-multer-and-expressjs-zthuy53oi). – epasos_573 Apr 07 '23 at 04:56

0 Answers0