hrms-api-recruit/Services/MinIOService.cs

115 lines
3.6 KiB
C#
Raw Normal View History

2023-03-24 14:24:35 +07:00
using System;
using System.Collections.Generic;
using System.Linq;
2023-03-25 20:03:27 +07:00
using System.Net.Http.Headers;
2023-03-24 14:24:35 +07:00
using System.Threading.Tasks;
2023-03-25 20:03:27 +07:00
using Amazon.S3;
using Amazon.S3.Model;
2023-03-24 14:24:35 +07:00
using BMA.EHR.Recruit.Service.Core;
using BMA.EHR.Recruit.Service.Data;
2023-03-25 20:03:27 +07:00
using BMA.EHR.Recruit.Service.Models.Documents;
2023-03-24 14:24:35 +07:00
using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Recruit.Service.Services
{
public class MinIOService
{
#region " Fields "
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _webHostEnvironment;
2023-03-25 20:03:27 +07:00
private readonly AmazonS3Client _s3Client;
private string _bucketName = string.Empty;
#endregion
#region " Constructors "
public MinIOService(ApplicationDbContext context,
IConfiguration configuration,
IWebHostEnvironment webHostEnvironment)
{
_context = context;
_configuration = configuration;
_webHostEnvironment = webHostEnvironment;
var config = new AmazonS3Config
{
ServiceURL = _configuration["MinIO:Endpoint"],
ForcePathStyle = true
};
_s3Client = new AmazonS3Client(_configuration["MinIO:AccessKey"], _configuration["MinIO:SecretKey"], config);
this._bucketName = _configuration["MinIO:BucketName"] ?? "bma-recruit";
}
#endregion
#region " Methods "
public async Task<Document> UploadFile(IFormFile file, string newFileName = "")
{
var fileName = "";
var fileExt = Path.GetExtension(file.FileName);
if (newFileName != "")
fileName = $"{newFileName}";
else
fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
if (!Directory.Exists(tmpDir))
Directory.CreateDirectory(tmpDir);
var tmpFile = Path.Combine(tmpDir, $"tmp_{DateTime.Now.ToString("ddMMyyyyHHmmss")}{fileExt}");
try
{
using (var ms = new MemoryStream())
{
var id = Guid.NewGuid();
file.CopyTo(ms);
var fileBytes = ms.ToArray();
System.IO.MemoryStream filestream = new System.IO.MemoryStream(fileBytes);
var request = new PutObjectRequest
{
BucketName = _bucketName,
Key = id.ToString("D"),
InputStream = filestream,
ContentType = file.ContentType,
CannedACL = S3CannedACL.PublicRead
};
await _s3Client.PutObjectAsync(request);
// create document object
var doc = new Document()
{
FileName = fileName,
FileType = file.ContentType,
FileSize = Convert.ToInt32(file.Length),
ObjectRefId = id,
CreatedDate = DateTime.Now
};
await _context.Documents.AddAsync(doc);
await _context.SaveChangesAsync();
return doc;
}
}
catch
{
throw;
}
finally
{
File.Delete(tmpFile);
}
}
2023-03-24 14:24:35 +07:00
#endregion
}
}