using Amazon.Runtime; using Amazon.S3; using Amazon.S3.Transfer; using Amazon; using Amazon.S3.Model; using Dapper; using Microsoft.AspNetCore.JsonPatch; using MisIngredientesVue.Core.Exceptions; using MisIngredientesVue.Core.Extensions; using MisIngredientesVue.Core.Models; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MisIngredientesVue.Core.Services { public interface IFileStorageService { Task SaveFile(string id, string folder, byte[] contents); Task LoadFile(string id, string folder); Task FileExists(string id, string folder); } public class FileStorageService : IFileStorageService { AmazonS3Client _s3Client; public FileStorageService() { _s3Client = new AmazonS3Client("AKIAIIQHM2OQTAIIL62A", "jPlXrQqtAVQgwM5VSyS613BhwHNG6mC8PJwzcbfn", Amazon.RegionEndpoint.USEast1); } public async Task SaveFile(string id, string folder, byte[] contents) { using (var memStream = new MemoryStream(contents)) { memStream.Position = 0; var fileTransferUtility = new TransferUtility(_s3Client); await fileTransferUtility.UploadAsync(memStream, folder, id); } } public async Task FileExists(string id, string folder) { try { var response = await _s3Client.GetObjectMetadataAsync(new GetObjectMetadataRequest() { BucketName = folder, Key = id }); return true; } catch (Amazon.S3.AmazonS3Exception ex) { if (ex.StatusCode == System.Net.HttpStatusCode.NotFound) return false; //status wasn't not found, so throw the exception throw; } } public async Task LoadFile(string id, string folder) { using (MemoryStream ms = new MemoryStream()) { byte[] buffer = new byte[16 * 1024]; var fileTransferUtility = new TransferUtility(_s3Client); var stream = await fileTransferUtility.OpenStreamAsync(folder, id); int read; while ((read = stream.Read(buffer, 0, buffer.Length)) > 0) { ms.Write(buffer, 0, read); } return ms.ToArray(); } } } }