Skip to content

Instantly share code, notes, and snippets.

@renatocfrancisco
Last active March 2, 2022 00:46
Show Gist options
  • Save renatocfrancisco/e074a6960fecb7ccb92c58cac8f93690 to your computer and use it in GitHub Desktop.
Save renatocfrancisco/e074a6960fecb7ccb92c58cac8f93690 to your computer and use it in GitHub Desktop.
Asp.Net Annotations

ASP.NET Annotations

IHostEnvironment

//no inicio do controller
private readonly ImageContext _context;

private readonly IWebHostEnvironment _hostEnvironment;

public ImageModelsController(IWebHostEnvironment hostEnvironment, ImageContext context)
{
  _hostEnvironment = hostEnvironment;
  _context = context;
}

Form em um index quando inserir uma imagem (CREATE)

<form asp-action="Create" enctype="multipart/form-data">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <div class="form-group">
                <label asp-for="Titulo" class="control-label"></label>
                <input asp-for="Titulo" class="form-control" />
                <span asp-validation-for="Titulo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ImageFile" class="control-label"></label>
                <input asp-for="ImageFile" accept="image/*" />
                <span asp-validation-for="ImageFile" class="text-danger"></span>
            </div>
            <div class="form-group">
                <input type="submit" value="Create" class="btn btn-primary" />
            </div>
</form>

Form para editar objeto com imagem (EDIT)

<form asp-action="Edit" enctype="multipart/form-data">
            <input asp-for="NomeImagem" hidden /> 
            //input para inserir o NomeImagem escondido para quando o usuário não enviar novas imagens
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
            <input type="hidden" asp-for="Id" />
            <div class="form-group">
                <label asp-for="Titulo" class="control-label"></label>
                <input asp-for="Titulo" class="form-control" />
                <span asp-validation-for="Titulo" class="text-danger"></span>
            </div>
            <div class="form-group">
                <label asp-for="ImageFile" class="control-label"></label>
                <input asp-for="ImageFile" accept="image/*" />
                <span asp-validation-for="ImageFile" class="text-danger"></span>
            </div>
            <dt class="col-sm-2">
                Imagem Enviada
            </dt>
            <dt class="col-sm-10">
                <img src="@("~/Imagens/"+Model.Id+"/"+Model.NomeImagem)" asp-append-version="true" width="100" height="100" />
            </dt>
            <div class="form-group">
                <input type="submit" value="Save" class="btn btn-primary" />
            </div>
        </form>

Criar efmigrationhistory em um banco de dados

CREATE TABLE __efmigrationshistory (
MigrationId VARCHAR(150) NOT NULL COLLATE 'utf8_general_ci',
ProductVersion VARCHAR(32) NOT NULL COLLATE 'utf8_general_ci',
PRIMARY KEY (MigrationId) USING BTREE
)
COLLATE='utf8mb4_0900_ai_ci'
ENGINE=InnoDB;

Padrão de classe Context

public ImageContext(DbContextOptions<ImageContext> options) : base(options)
   {

   }
public DbSet<ImageModel> Images { get; set; }

Ajustar o appsettings.json

"AllowedHosts": "*",
"ConexaoMySqlLocal": {
"MySqlConnectionString": "Server=localhost;DataBase=bdteste;Uid=root;Pwd=1234"
}

Configurar o startup.cs

var connection = Configuration["ConexaoMySqlLocal:MySqlConnectionString"];
services.AddDbContext<TesteContexto>(Options => Options.UseMySQL(connection));

Deletar Imagem depois de upload

///deletar imagem no POST: Image/Delete/5 (DeleteConfirmed)
var imageModel = await _context.Images.FindAsync(id);
var imagePath = Path.Combine(_hostEnvironment.WebRootPath, "Imagens", imageModel.NomeImagem);
  if (System.IO.File.Exists(imagePath))
  {
    System.IO.File.Delete(imagePath);
  }
//imagem é deletada

Mostrar imagem em um index

<img src="@("~/Imagens/"+item.NomeImagem)" asp-append-version="true" width="100" height="100" />

ou

<img src="@("~/Imagens/"+Model.Id+"/"+Model.NomeImagem)" asp-append-version="true" width="100" height="100" />

Salvar Imagens no wwwroot/Imagens (ou em outra pasta)

string wwwRootPath = _hostEnvironmnet.WebRootPath;
string fileName = Path.GetFileNameWithoutExtension(imageModel.ImageFile.FileName);
string extension = Path.GetExtension(imageModel.ImageFile.FileName);

imageModel.NomeImagem = fileName += DateTime.Now.ToString("yymmssfff") + extension;
string path = Path.Combine(wwwRootPath + "/Imagens/", fileName);
using (var fileStream = new FileStream(path, FileMode.Create))
{
  await imageModel.ImageFile.CopyToAsync(fileStream);
}
//Inserindo Imagem
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment