Skip to content

Instantly share code, notes, and snippets.

@jotredev
Last active January 18, 2023 02:10
Show Gist options
  • Save jotredev/f0e08525259f9b0f4e0970a731bedf32 to your computer and use it in GitHub Desktop.
Save jotredev/f0e08525259f9b0f4e0970a731bedf32 to your computer and use it in GitHub Desktop.
Subir archivos a Cludinary con Node JS, Express
import cloudinary from "cloudinary";
cloudinary.v2.config({
cloud_name: [CLOUDINARY_NAME],
api_key: [CLOUDINARY_API_KEY],
api_secret: [CLOUDINARY_API_SECRET],
});
// Subir archivo a cloudinary
export const uploadAvatar = async (file) => {
return await cloudinary.v2.uploader.upload(file, {
folder: "Avatars", // Carpeta de Cloudinary donde lo subiremos
});
};
// Eliminar archivo de cloudinary
export const deleteFile = async (public_id) => {
return await cloudinary.v2.uploader.destroy(public_id);
};
import fileUpload from "express-fileupload";
// Poder subir archivos
app.use(
fileUpload({
useTempFiles: true, // Usar archivos temporales
tempFileDir: "./src/uploads",
})
);
import User from "./userModel.js";
import { uploadAvatar, deleteFile } from "./cloudinary.js";
import fs from "fs-extra";
export const changeAvatar = async (req, res) => {
const { user } = req;
const { userId } = req.params;
if (!req.files.image) {
return res.status(400).json({
response: "error",
msg: "Image is required",
type: "image-is-required",
});
}
const getUserById = await User.findById(userId);
if (!getUserById) {
return res.status(404).json({
response: "error",
msg: "User not found",
type: "user-not-found",
});
}
try {
// Verificamos si el usuario ya tiene una imagen
if (getUserById.avatar.url) {
// Eliminamos la imagen anterior
await deleteFile(getUserById.avatar.publicId);
}
// Subimos la imagen a cloudinary
const result = await uploadAvatar(req.files.image.tempFilePath);
// Una vez subida la imagen eliminamos el archivo temporal del servidor
fs.remove(req.files.image.tempFilePath);
// Actualizamos la imagen del usuario
getUserById.avatar.url = result.secure_url;
getUserById.avatar.publicId = result.public_id;
return res
.status(201)
.json({ response: "ok", avatar: savedUser.avatar });
} catch (error) {
console.log(error);
return res
.status(500)
.json({ response: "error", type: "server-error", msg: "Server error" });
}
};
@jotredev
Copy link
Author

Dependencias necesarias en el backend

  • fs-extra(v11.1.0)
  • express-fileupload(v1.4.0)
  • cloudinary(v1.33.0)

Debemos tener el siguiente modelado en la colección de users en MongoDB

avatar: {
     url: String,
     publicId: String
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment