Skip to content

Commit 3445c83

Browse files
Seção 12: Upload e Tratamento de Imagem
1 parent 3133187 commit 3445c83

14 files changed

Lines changed: 339 additions & 166 deletions

File tree

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ bld/
3131
[Oo]bj/
3232
[Ll]og/
3333
[Ll]ogs/
34+
Resources/
3435

3536
# Visual Studio 2015/2017 cache/options directory
3637
.vs/

Back/src/BrnEventos.API/Controllers/EventosController.cs

Lines changed: 67 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,9 @@
44
using System;
55
using Microsoft.AspNetCore.Http;
66
using BrnEventos.Application.Dtos;
7+
using System.IO;
8+
using Microsoft.AspNetCore.Hosting;
9+
using System.Linq;
710

811
namespace BrnEventos.API.Controllers
912
{
@@ -12,10 +15,12 @@ namespace BrnEventos.API.Controllers
1215
public class EventosController : ControllerBase
1316
{
1417
private readonly IEventoService _eventoService;
18+
private readonly IWebHostEnvironment _hostEnvironment;
1519

16-
public EventosController(IEventoService eventoService)
20+
public EventosController(IEventoService eventoService, IWebHostEnvironment hostEnvironment)
1721
{
1822
_eventoService = eventoService;
23+
_hostEnvironment = hostEnvironment;
1924
}
2025

2126
[HttpGet]
@@ -68,6 +73,31 @@ public async Task<IActionResult> GetByTema(string tema)
6873
}
6974
}
7075

76+
[HttpPost("upload-image/{eventoId}")]
77+
public async Task<IActionResult> UploadImage(int eventoId)
78+
{
79+
try
80+
{
81+
var evento = await _eventoService.GetEventoByIdAsync(eventoId, true);
82+
if (evento == null) return NoContent();
83+
84+
var file = Request.Form.Files[0];
85+
if (file.Length > 0)
86+
{
87+
DeleteImage(evento.ImagemURL);
88+
evento.ImagemURL = await SaveImage(file);
89+
}
90+
var EventoRetorno = await _eventoService.UpdateEvento(eventoId, evento);
91+
92+
return Ok(EventoRetorno);
93+
}
94+
catch (Exception ex)
95+
{
96+
return this.StatusCode(StatusCodes.Status500InternalServerError,
97+
$"Erro ao tentar adicionar a IMAGEM! Erro: {ex.Message}");
98+
}
99+
}
100+
71101
[HttpPost]
72102
public async Task<IActionResult> Post(EventoDto model)
73103
{
@@ -110,15 +140,48 @@ public async Task<IActionResult> Delete(int id)
110140
var evento = await _eventoService.GetEventoByIdAsync(id, true);
111141
if (evento == null) return NoContent();
112142

113-
return await _eventoService.DeleteEvento(id)
114-
? Ok(new { menssage = "Deletado" })
115-
: throw new Exception("Ocorreu um erro não específico ao tentar deletar o Evento");
143+
if (await _eventoService.DeleteEvento(id))
144+
{
145+
DeleteImage(evento.ImagemURL);
146+
return Ok(new { menssage = "Deletado" });
147+
}
148+
else
149+
{
150+
throw new Exception("Ocorreu um erro não específico ao tentar deletar o Evento");
151+
}
116152
}
117153
catch (Exception ex)
118154
{
119155
return this.StatusCode(StatusCodes.Status500InternalServerError,
120156
$"Erro ao tentar deletar eventos! Erro: {ex.Message}");
121157
}
122158
}
159+
160+
[NonAction]
161+
public async Task<string> SaveImage(IFormFile imageFile)
162+
{
163+
string imageName = new String(Path.GetFileNameWithoutExtension(imageFile.FileName)
164+
.Take(10)
165+
.ToArray()
166+
).Replace(' ', '-');
167+
168+
imageName = $"{imageName}{DateTime.UtcNow.ToString("yymmssfff")}{Path.GetExtension(imageFile.FileName)}";
169+
170+
var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, @"Resources/images", imageName);
171+
172+
using (var fileStream = new FileStream(imagePath, FileMode.Create))
173+
{
174+
await imageFile.CopyToAsync(fileStream);
175+
}
176+
return imageName;
177+
}
178+
179+
[NonAction]
180+
public void DeleteImage(string imageName)
181+
{
182+
var imagePath = Path.Combine(_hostEnvironment.ContentRootPath, @"Resources/images", imageName);
183+
if (System.IO.File.Exists(imagePath))
184+
System.IO.File.Delete(imagePath);
185+
}
123186
}
124187
}

Back/src/BrnEventos.API/Program.cs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
12
using System;
23
using System.Collections.Generic;
34
using System.Linq;
@@ -23,4 +24,4 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
2324
webBuilder.UseStartup<Startup>();
2425
});
2526
}
26-
}
27+
}

Back/src/BrnEventos.API/Startup.cs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,15 @@
66
using BrnGeral.Persistence;
77
using Microsoft.AspNetCore.Builder;
88
using Microsoft.AspNetCore.Hosting;
9+
using Microsoft.AspNetCore.Http;
910
using Microsoft.EntityFrameworkCore;
1011
using Microsoft.Extensions.Configuration;
1112
using Microsoft.Extensions.DependencyInjection;
13+
using Microsoft.Extensions.FileProviders;
1214
using Microsoft.Extensions.Hosting;
1315
using Microsoft.OpenApi.Models;
1416
using System;
17+
using System.IO;
1518

1619
namespace BrnEventos.API
1720
{
@@ -82,6 +85,12 @@ public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
8285
.AllowAnyMethod()
8386
.AllowAnyOrigin());
8487

88+
app.UseStaticFiles(new StaticFileOptions()
89+
{
90+
FileProvider = new PhysicalFileProvider(Path.Combine(Directory.GetCurrentDirectory(), "Resources")),
91+
RequestPath = new PathString("/Resources")
92+
});
93+
8594
app
8695
.UseEndpoints(endpoints =>
8796
{

Back/src/BrnEventos.Application/Dtos/EventoDto.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -24,9 +24,8 @@ public class EventoDto
2424
Display(Name = "Qtd Pessoas")]
2525
public int QtdPessoas { get; set; }
2626

27-
[Required(ErrorMessage = "O Campo {0} é obrigatório!")]
2827
[RegularExpression(@".*\.(gif|jpe?g|bmp|png)$",
29-
ErrorMessage = "Não é uma imagem válida. (gif, jpg, jpeg, bmp, png)")]
28+
ErrorMessage = "Não é uma imagem válida. (gif, jpg, jpeg, bmp, png)")]
3029
public string ImagemURL { get; set; }
3130

3231
[Required(ErrorMessage = "O Campo {0} é obrigatório!"),

0 commit comments

Comments
 (0)