MinIO Service

This commit is contained in:
Suphonchai Phoonsawat 2023-03-25 20:03:27 +07:00
parent e33c19ae8a
commit bdd327cce2
43 changed files with 2092 additions and 1447 deletions

View file

@ -1,165 +0,0 @@
using BMA.EHR.Recruit.Service.Core;
using BMA.EHR.Recruit.Service.Data;
using Microsoft.EntityFrameworkCore;
using MongoDB.Driver.GridFS;
using MongoDB.Driver;
using BMA.EHR.Recruit.Service.Models.Documents;
using System.Net.Http.Headers;
using BMA.EHR.Recruit.Service.Responses.Document;
using MongoDB.Bson;
namespace BMA.EHR.Recruit.Service.Services
{
public class DocumentService
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _webHostEnvironment;
private const string MONGO_DATABASE = "bma-recruit";
public DocumentService(ApplicationDbContext context,
IConfiguration configuration,
IWebHostEnvironment webHostEnvironment)
{
_context = context;
_configuration = configuration;
_webHostEnvironment = webHostEnvironment;
}
public string MongoConnectionString
{
get => _configuration.GetConnectionString("MongoConnection");
}
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
{
// upload to tmp
using (var stream = new FileStream(tmpFile, FileMode.Create))
{
file.CopyTo(stream);
}
var mongo = new MongoClient(MongoConnectionString);
var bucket = new GridFSBucket(mongo.GetDatabase(MONGO_DATABASE));
using (var fs = new FileStream(tmpFile, FileMode.Open, FileAccess.Read))
{
var fileId = bucket.UploadFromStream(fileName, fs);
var info = new FileInfo(tmpFile);
try
{
var doc = new Document()
{
FileName = fileName,
FileType = file.ContentType,
FileSize = Convert.ToInt32(file.Length),
ObjectRefId = fileId.ToString(),
CreatedDate = DateTime.Now
};
await _context.Documents.AddAsync(doc);
await _context.SaveChangesAsync();
return doc;
}
catch
{
bucket.Delete(fileId);
throw new Exception(GlobalMessages.CannotInsertToDatabase);
}
}
}
catch
{
throw;
}
finally
{
System.IO.File.Delete(tmpFile);
}
}
public async Task DeleteFile(Guid fileId)
{
try
{
var doc = await _context.Documents.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == fileId);
if (doc == null)
throw new Exception(GlobalMessages.FileNotFoundOnServer);
var mongo = new MongoClient(MongoConnectionString);
var bucket = new GridFSBucket(mongo.GetDatabase(MONGO_DATABASE));
bucket.Delete(ObjectId.Parse(doc.ObjectRefId));
_context.Documents.Remove(doc);
await _context.SaveChangesAsync();
}
catch
{
throw;
}
}
public async Task<FileDownloadResponse> DownloadFile(Guid fileId)
{
var tmpDir = Path.Combine(_webHostEnvironment.ContentRootPath, "tmp");
if (!Directory.Exists(tmpDir))
Directory.CreateDirectory(tmpDir);
var tmpFile = Path.Combine(tmpDir, $"tmp_{DateTime.Now.ToString("ddMMyyyyHHmmss")}");
try
{
var doc = await _context.Documents.AsQueryable()
.FirstOrDefaultAsync(x => x.Id == fileId);
if (doc == null)
throw new Exception(GlobalMessages.FileNotFoundOnServer);
var fileExt = Path.GetExtension(doc.FileName);
tmpFile = tmpFile + fileExt;
var mongo = new MongoClient(MongoConnectionString);
var bucket = new GridFSBucket(mongo.GetDatabase(MONGO_DATABASE));
var f = bucket.DownloadAsBytes(ObjectId.Parse(doc.ObjectRefId));
return new FileDownloadResponse
{
FileName = doc.FileName,
FileType = doc.FileType,
FileContent = f
};
}
catch
{
throw;
}
finally
{
File.Delete(tmpFile);
}
}
}
}

View file

@ -1,9 +1,13 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using Amazon.S3;
using Amazon.S3.Model;
using BMA.EHR.Recruit.Service.Core;
using BMA.EHR.Recruit.Service.Data;
using BMA.EHR.Recruit.Service.Models.Documents;
using Microsoft.EntityFrameworkCore;
namespace BMA.EHR.Recruit.Service.Services
@ -15,6 +19,96 @@ namespace BMA.EHR.Recruit.Service.Services
private readonly ApplicationDbContext _context;
private readonly IConfiguration _configuration;
private readonly IWebHostEnvironment _webHostEnvironment;
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);
}
}
#endregion
}