Skip to content

Commit

Permalink
Subida de archivos
Browse files Browse the repository at this point in the history
  • Loading branch information
rjvelazco committed Nov 28, 2020
1 parent 96162c1 commit 8478d6a
Show file tree
Hide file tree
Showing 10 changed files with 298 additions and 2 deletions.
4 changes: 3 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
node_modules/
node_modules/
tmp
uploads/
29 changes: 29 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"bcrypt": "^5.0.0",
"body-parser": "^1.19.0",
"express": "^4.17.1",
"express-fileupload": "^1.2.0",
"google-auth-library": "^6.1.3",
"jsonwebtoken": "^8.5.1",
"mongoose": "^5.10.14",
Expand Down
3 changes: 3 additions & 0 deletions public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,9 @@
</head>

<body>

<!-- <img src="http://localhost:3000/imagen/productos/5fbdae27e80cb40c486aab9f-470.png?token=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1c3VhcmlvIjp7InJvbGUiOiJBRE1JTl9ST0xFIiwiZXN0YWRvIjp0cnVlLCJnb29nbGUiOmZhbHNlLCJfaWQiOiI1ZmIwM2RjYWNhOGI2MTA2MjAxMjY0OGQiLCJub21icmUiOiJUZXN0IDEiLCJlbWFpbCI6InRlc3QxQGhvdG1haWwuY29tIiwiX192IjowLCJpbWciOiI1ZmIwM2RjYWNhOGI2MTA2MjAxMjY0OGQtNDA5LmpwZyJ9LCJpYXQiOjE2MDY1OTg2OTcsImV4cCI6MTYwNjc3MTQ5N30.W7E4yX9CoZV003kFhXmJITe9O83ZaO2QBOvPZcbaF6Y" alt=""> -->

<div class="g-signin2" data-onsuccess="onSignIn"></div>

<a href="#" onclick="signOut();">Sign out</a>
Expand Down
Binary file added server/assets/no-image.jpg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
26 changes: 25 additions & 1 deletion server/middlewares/authentication.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,32 @@ let verificaAdmin_Role = (req, res, next) => {
next();
}

// ========================
// Verifica token en imagen
// ========================

let verificaTokenImg = (req, res, next) => {
let token = req.query.token;

jwt.verify(token, process.env.SEED, (err, decoded) => {
if (err) {
return res.status(400).json({
ok: false,
err: {
message: 'token no valido',
token
}
});
};
// req.usuario = decoded.usuario;
next();
});
}



module.exports = {
verificaToken,
verificaAdmin_Role
verificaAdmin_Role,
verificaTokenImg
}
1 change: 1 addition & 0 deletions server/models/producto.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ var productoSchema = new Schema({
nombre: { type: String, required: [true, 'El nombre es necesario'] },
precioUni: { type: Number, required: [true, 'El precio únitario es necesario'] },
descripcion: { type: String, required: false },
img: { type: String, required: false },
disponible: { type: Boolean, required: true, default: true },
categoria: { type: Schema.Types.ObjectId, ref: 'Categoria', required: true },
usuario: { type: Schema.Types.ObjectId, ref: 'Usuario' }
Expand Down
29 changes: 29 additions & 0 deletions server/routes/imagenes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
const express = require('express');

const fs = require('fs');
const path = require('path');

let app = express();

let { verificaTokenImg } = require('../middlewares/authentication')

app.get('/imagen/:tipo/:img', verificaTokenImg, (req, res) => {

let tipo = req.params.tipo;
let img = req.params.img;

let pathImg = path.resolve(__dirname, `../../uploads/${tipo}/${img}`);
let noImagePath = path.resolve(__dirname, '../assets/no-image.jpg')


if (fs.existsSync(pathImg)) {
return res.sendFile(pathImg);
};
return res.sendFile(noImagePath);

});




module.exports = app;
2 changes: 2 additions & 0 deletions server/routes/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ app.use(require('./usuario'));
app.use(require('./login'));
app.use(require('./categoria'));
app.use(require('./producto'));
app.use(require('./upload'));
app.use(require('./imagenes'));
// app.use(require('./producto'));

module.exports = app;
205 changes: 205 additions & 0 deletions server/routes/upload.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
const express = require('express');
const fileUpload = require('express-fileupload');

const app = express();

const Usuario = require('../models/usuario');
const Producto = require('../models/producto');
const fs = require('fs');
const path = require('path');

app.use(fileUpload({ useTempFiles: true }));


app.put('/upload/:tipo/:id', (req, res) => {

if (!fs.existsSync(path.resolve(__dirname, '../../uploads'))) {
crearDirectorio(res);
};

let tipo = req.params.tipo;
let id = req.params.id;

if (!req.files) {
return res.status(400).json({
ok: false,
err: {
message: 'No se ha seleccionado ningun archivo'
}
});
};

// Validar tipo
let tiposValidos = ['productos', 'usuarios'];
if (tiposValidos.indexOf(tipo) < 0) {
return res.status(400).json({
ok: false,
err: {
message: 'Las tipos permitidos son: ' + tiposValidos.join(', '),
tipo
}
})
}

let archivo = req.files.archivo;
let nombreCortado = archivo.name.split('.');
let extension = nombreCortado[nombreCortado.length - 1];

// Extensiones permitidas
let extensionesValidas = ['png', 'jpg', 'gif', 'jpeg'];
if (extensionesValidas.indexOf(extension) < 0) {
return res.status(400).json({
ok: false,
err: {
message: 'Las extensiones validas son: ' + extensionesValidas.join(', '),
ext: extension
}
})
};

// Cambiar nombre al archivo
let nombreArchivo = `${id}-${new Date().getMilliseconds()}.${extension}`;

archivo.mv(`./uploads/${tipo}/${nombreArchivo}`, (err) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
};

// Aqui, imagen cargada
if (tipo === 'usuarios') {
imagenUsuario(id, res, nombreArchivo);
} else {
imagenProducto(id, res, nombreArchivo)
}
});
});

function imagenUsuario(id, res, nombreArchivo) {

Usuario.findById(id, (err, usuarioDB) => {
if (err) {
borrarArchivo('usuarios', nombreArchivo);
return res.status(500).json({
ok: false,
err
});
};

if (!usuarioDB) {
borrarArchivo('usuarios', nombreArchivo);
return res.status(400).json({
ok: false,
err: {
message: 'Usuario no existe'
}
});
}

borrarArchivo('usuarios', usuarioDB.img);


usuarioDB.img = nombreArchivo;
usuarioDB.save((err, usuarioGuardado) => {
if (err) {
return res.status(500).json({
ok: false,
err
})
};
return res.json({
ok: true,
usuario: usuarioGuardado,
img: nombreArchivo
})
});

})

};

function imagenProducto(id, res, nombreArchivo) {

Producto.findById(id, (err, productoDB) => {

if (err) {
borrarArchivo('productos', nombreArchivo);
return res.status(500).json({
ok: false,
err
})
};

if (!productoDB) {
borrarArchivo('productos', nombreArchivo);
return res.status(400).json({
ok: false,
err: {
message: 'ID no existe'
}
});
};


borrarArchivo('productos', productoDB.img)

productoDB.img = nombreArchivo;

productoDB.save((err, productoGuardado) => {
if (err) {
return res.status(500).json({
ok: false,
err
});
};

return res.json({
ok: true,
producto: productoGuardado
})
})

});


};

const borrarArchivo = (tipo, nombreImagen) => {
let pathUrl = path.resolve(__dirname, `../../uploads/${tipo}/${nombreImagen}`);

if (fs.existsSync(pathUrl)) {
fs.unlinkSync(pathUrl);
}

};

const crearDirectorio = (res) => {
fs.mkdir(path.resolve(__dirname, '../../uploads'), { recursive: true }, (err) => {
if (err) {
return res.status(500).json({
ok: false,
err
})
}
fs.mkdir(path.resolve(__dirname, '../../uploads/usuarios'), { recursive: true }, (err) => {
if (err) {
return res.status(500).json({
ok: false,
err
})
}
});
fs.mkdir(path.resolve(__dirname, '../../uploads/productos'), { recursive: true }, (err) => {
if (err) {
return res.status(500).json({
ok: false,
err
})
}
})
});
};

module.exports = app;

0 comments on commit 8478d6a

Please sign in to comment.