61 lines
1.6 KiB
TypeScript
61 lines
1.6 KiB
TypeScript
|
|
import {
|
||
|
|
Controller,
|
||
|
|
Delete,
|
||
|
|
Get,
|
||
|
|
HttpException,
|
||
|
|
HttpStatus,
|
||
|
|
Param,
|
||
|
|
Post,
|
||
|
|
Res,
|
||
|
|
UploadedFile,
|
||
|
|
UseInterceptors,
|
||
|
|
} from '@nestjs/common';
|
||
|
|
import { FileInterceptor } from '@nestjs/platform-express';
|
||
|
|
import { Response } from 'express';
|
||
|
|
import * as fs from 'fs';
|
||
|
|
import { diskStorage } from 'multer';
|
||
|
|
import * as path from 'path';
|
||
|
|
|
||
|
|
@Controller('carousel')
|
||
|
|
export class CarouselController {
|
||
|
|
private images: string[] = [];
|
||
|
|
|
||
|
|
@Post('/imagenes')
|
||
|
|
@UseInterceptors(
|
||
|
|
FileInterceptor('file', {
|
||
|
|
storage: diskStorage({
|
||
|
|
destination: './public',
|
||
|
|
filename: function (req, file, cb) {
|
||
|
|
cb(null, file.originalname);
|
||
|
|
},
|
||
|
|
}),
|
||
|
|
}),
|
||
|
|
)
|
||
|
|
async addImage(@UploadedFile() file) {
|
||
|
|
return {msg: 'Imagen guardada con exito :)'}
|
||
|
|
}
|
||
|
|
|
||
|
|
@Delete('/imagenes/:nombreArchivo')
|
||
|
|
async deleteImage(@Param('nombreArchivo') nombreArchivo: string) {
|
||
|
|
try {
|
||
|
|
await fs.promises.unlink(`./public/${nombreArchivo}`);
|
||
|
|
return { message: 'Imagen eliminada exitosamente' };
|
||
|
|
} catch (err) {
|
||
|
|
throw new Error('Error al eliminar la imagen');
|
||
|
|
}
|
||
|
|
}
|
||
|
|
|
||
|
|
@Get('/imagenes')
|
||
|
|
async getImages(@Res() res: Response) {
|
||
|
|
// Leer el directorio 'public' para obtener el nombre de todos los archivos
|
||
|
|
const fileNames = await fs.promises.readdir('./public');
|
||
|
|
// Generar la URL para cada archivo y agregarla a un arreglo
|
||
|
|
const baseUrl = 'http://localhost:5089'; // reemplaza con la URL de tu servidor
|
||
|
|
const imageUrls = fileNames.map(
|
||
|
|
(fileName) => `${baseUrl}/public/${fileName}`,
|
||
|
|
);
|
||
|
|
// Devolver el arreglo de URLs como respuesta
|
||
|
|
return res.json(imageUrls);
|
||
|
|
}
|
||
|
|
}
|