Last active
January 18, 2023 02:10
-
-
Save jotredev/f0e08525259f9b0f4e0970a731bedf32 to your computer and use it in GitHub Desktop.
Subir archivos a Cludinary con Node JS, Express
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import fileUpload from "express-fileupload"; | |
// Poder subir archivos | |
app.use( | |
fileUpload({ | |
useTempFiles: true, // Usar archivos temporales | |
tempFileDir: "./src/uploads", | |
}) | |
); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" }); | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Dependencias necesarias en el backend
Debemos tener el siguiente modelado en la colección de users en MongoDB