Last active
May 20, 2021 11:14
-
-
Save Whistler092/3bdc1f1fd0c8b9b6622328652479aea4 to your computer and use it in GitHub Desktop.
Upload files into Azure Blob Storage
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
using System; | |
using System.Threading.Tasks; | |
using AutoMapper; | |
using Microsoft.AspNetCore.Mvc; | |
using API.DTOs; | |
using API.Entidades; | |
using API.Utilidades; | |
namespace API.Controllers | |
{ | |
[Route("api/actores")] | |
[ApiController] | |
public class ActoresController : ControllerBase | |
{ | |
private readonly ApplicationDbContext context; | |
private readonly IMapper mapper; | |
private readonly IAlmacenadorArchivos almacenadorArchivos; | |
private readonly string contenedor = "actores"; | |
public ActoresController(ApplicationDbContext context, IMapper mapper, IAlmacenadorArchivos almacenadorArchivos) | |
{ | |
this.context = context; | |
this.mapper = mapper; | |
this.almacenadorArchivos = almacenadorArchivos; | |
} | |
[HttpPost] | |
public async Task<ActionResult> Post([FromForm] ActorCreacionDTO actorCreacionDTO) | |
{ | |
var actor = mapper.Map<Actor>(actorCreacionDTO); | |
if(actorCreacionDTO.Foto != null) | |
{ | |
actor.Foto = await almacenadorArchivos.GuardarArchivo(contenedor, actorCreacionDTO.Foto); | |
} | |
context.Add(actor); | |
await context.SaveChangesAsync(); | |
return NoContent(); | |
} | |
} | |
} |
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
using System; | |
using System.IO; | |
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Hosting; | |
using Microsoft.AspNetCore.Http; | |
namespace API.Utilidades | |
{ | |
public class AlmacenadorArchivosLocal : IAlmacenadorArchivos | |
{ | |
private readonly IWebHostEnvironment env; | |
private readonly IHttpContextAccessor httpContextAccessor; | |
public AlmacenadorArchivosLocal(IWebHostEnvironment env, IHttpContextAccessor httpContextAccessor) | |
{ | |
this.env = env; | |
this.httpContextAccessor = httpContextAccessor; | |
} | |
public Task BorrarArchivo(string ruta, string contenedor) | |
{ | |
if (string.IsNullOrEmpty(ruta)) | |
{ | |
return Task.CompletedTask; | |
} | |
var nombreArchivo = Path.GetFileName(ruta); | |
var directorioArchivo = Path.Combine(env.WebRootPath, contenedor, nombreArchivo); | |
if (File.Exists(directorioArchivo)) | |
{ | |
File.Delete(directorioArchivo); | |
} | |
return Task.CompletedTask; | |
} | |
public async Task<string> EditarArchivo(string contenedor, IFormFile archivo, string ruta) | |
{ | |
await BorrarArchivo(ruta, contenedor); | |
return await GuardarArchivo(contenedor, archivo); | |
} | |
public async Task<string> GuardarArchivo(string contenedor, IFormFile archivo) | |
{ | |
var extension = Path.GetExtension(archivo.FileName); | |
var nombreArchivo = $"{Guid.NewGuid()}{extension}"; | |
string folder = Path.Combine(env.WebRootPath, contenedor); | |
if (!Directory.Exists(folder)) | |
{ | |
Directory.CreateDirectory(folder); | |
} | |
string ruta = Path.Combine(folder, nombreArchivo); | |
using (var memoryStream = new MemoryStream()) | |
{ | |
await archivo.CopyToAsync(memoryStream); | |
var contenido = memoryStream.ToArray(); | |
await File.WriteAllBytesAsync(ruta, contenido); | |
} | |
var urlActual = $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host}"; | |
var rutaParaDb = Path.Combine(urlActual, contenedor, nombreArchivo).Replace("\\", "/"); | |
return rutaParaDb; | |
} | |
} | |
} |
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
using System; | |
using System.IO; | |
using System.Threading.Tasks; | |
using Azure.Storage.Blobs; | |
using Microsoft.AspNetCore.Http; | |
using Microsoft.Extensions.Configuration; | |
namespace API.Utilidades | |
{ | |
public class AlmacenadorAzureStorage : IAlmacenadorArchivos | |
{ | |
private string connectionString; | |
public AlmacenadorAzureStorage(IConfiguration configuration) | |
{ | |
connectionString = configuration.GetConnectionString("AzureStorage"); | |
} | |
public async Task<string> GuardarArchivo(string contenedor, IFormFile archivo) | |
{ | |
var cliente = new BlobContainerClient(connectionString, contenedor); | |
await cliente.CreateIfNotExistsAsync(); | |
cliente.SetAccessPolicy(Azure.Storage.Blobs.Models.PublicAccessType.Blob); | |
var extensions = Path.GetExtension(archivo.FileName); | |
var archivoNombre = $"{Guid.NewGuid()}{extensions}"; | |
var blob = cliente.GetBlobClient(archivoNombre); | |
await blob.UploadAsync(archivo.OpenReadStream()); | |
return blob.Uri.ToString(); | |
} | |
public async Task BorrarArchivo(string ruta, string contenedor) | |
{ | |
if (string.IsNullOrEmpty(ruta)) | |
{ | |
return; | |
} | |
var cliente = new BlobContainerClient(connectionString, contenedor); | |
await cliente.CreateIfNotExistsAsync(); | |
var archivo = Path.GetFileName(ruta); | |
var blob = cliente.GetBlobClient(archivo); | |
await blob.DeleteIfExistsAsync(); | |
} | |
public async Task<string> EditarArchivo(string contenedor, IFormFile archivo, string ruta) | |
{ | |
await BorrarArchivo(ruta, contenedor); | |
return await GuardarArchivo(contenedor, archivo); | |
} | |
} | |
} |
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
using System.Threading.Tasks; | |
using Microsoft.AspNetCore.Http; | |
namespace API.Utilidades | |
{ | |
public interface IAlmacenadorArchivos | |
{ | |
Task BorrarArchivo(string ruta, string contenedor); | |
Task<string> EditarArchivo(string contenedor, IFormFile archivo, string ruta); | |
Task<string> GuardarArchivo(string contenedor, IFormFile archivo); | |
} | |
} |
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
using API.Utilidades; | |
namespace API | |
{ | |
public class Startup | |
{ | |
public void ConfigureServices(IServiceCollection services) | |
{ | |
services.AddTransient<IAlmacenadorArchivos, AlmacenadorArchivosLocal>(); | |
services.AddHttpContextAccessor(); | |
} | |
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. | |
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) | |
{ | |
//NOTA: Crear la carpeta wwwroot | |
app.UseStaticFiles(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment