Created
September 9, 2022 22:18
-
-
Save akobashikawa/dbf2cc02a512d37d562f0f0b6d596a94 to your computer and use it in GitHub Desktop.
NodeJS controller para subir photo
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
controller.uploadPhoto = async function (req, res) { | |
try { | |
const form = new formidable.IncomingForm(); | |
form.parse(req, function (err, fields, files) { | |
if (err) throw err; | |
// photo debe enviado por el form | |
if (!files.photo) { | |
return res.status(402).json({ | |
message: 'Falta archivo enviado', | |
help: 'Uso: El archivo debe ser enviado en un multipart/form-data como photo' | |
}); | |
} | |
// guardar archivo | |
// console.log(util.inspect({ fields: fields, files: files })); | |
// console.log(files.photo.type); | |
const tmpPath = files.photo.path; | |
const photoName = files.photo.name; | |
const photoPath = `${MAMA_PHOTO_PATH}${photoName}`; | |
// console.log({ tmpPath, photoName, photoPath }); | |
fs.rename(tmpPath, photoPath, async function (err) { | |
if (err) { | |
fs.unlink(`${MAMA_PHOTO_PATH}${photoPath}`, function (err) { | |
if (err) { | |
return res.status(500).json({ | |
message: 'No se pudo eliminar el archivo subido pero no registrado' | |
}); | |
}; | |
}); | |
return res.status(500).json({ | |
message: 'No se pudo usar el archivo' | |
}); | |
}; | |
const photoUrl = `${MAMA_PHOTO_URL}${photoName}`; | |
// final | |
res.json({ | |
result: 'ok', | |
message: `Archivo subido: ${photoName}`, | |
url: photoUrl | |
}); | |
}); | |
}); | |
return; | |
} catch (error) { | |
console.log(error); | |
const result = self.getResultError(error); | |
return res.status(result.status).json(result); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment