From 6e72e69cfbef65c05005c793e0928b4d81224234 Mon Sep 17 00:00:00 2001 From: Syndamia Date: Tue, 11 May 2021 12:57:32 +0300 Subject: Added Cloudinary service and configured it --- ExamTemplate/Services/CloudinaryService.cs | 49 ++++++++++++++++++++++++++++++ ExamTemplate/Services/Services.csproj | 1 + 2 files changed, 50 insertions(+) create mode 100644 ExamTemplate/Services/CloudinaryService.cs (limited to 'ExamTemplate/Services') diff --git a/ExamTemplate/Services/CloudinaryService.cs b/ExamTemplate/Services/CloudinaryService.cs new file mode 100644 index 0000000..03b7265 --- /dev/null +++ b/ExamTemplate/Services/CloudinaryService.cs @@ -0,0 +1,49 @@ +using System.Collections.Generic; +using System.IO; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using CloudinaryDotNet; +using CloudinaryDotNet.Actions; +using Microsoft.AspNetCore.Http; + +namespace ExamTemplate.Services +{ + public class CloudinaryService + { + // Regex for getting the filename without (final) filename extension + // So, from image.png, it will match image, and from doc.my.txt will match doc.my + private static readonly Regex s_imageRegex = new(".*(?=\\.)"); + + private readonly Cloudinary _cloudinary; + + public CloudinaryService(string cloudName, string apiKey, string apiSecret) + { + this._cloudinary = new Cloudinary(new Account(cloudName, apiKey, apiSecret)); + } + + public async Task> UploadFilesToCloud(List formFiles) + { + List fileUrls = new(); + foreach (var formFile in formFiles) + { + string fileName = s_imageRegex.Match(formFile.FileName).ToString(); + + using var ms = new MemoryStream(); + formFile.CopyTo(ms); + byte[] formBytes = ms.ToArray(); + + RawUploadParams rawUploadParams = new() + { + File = new FileDescription(fileName, new MemoryStream(formBytes)), + PublicId = fileName, + UseFilename = true + }; + + RawUploadResult rawUploadResult = await this._cloudinary.UploadAsync(rawUploadParams); + fileUrls.Add(rawUploadResult.Url.AbsoluteUri); + } + + return fileUrls; + } + } +} diff --git a/ExamTemplate/Services/Services.csproj b/ExamTemplate/Services/Services.csproj index 9383013..eb60f3d 100644 --- a/ExamTemplate/Services/Services.csproj +++ b/ExamTemplate/Services/Services.csproj @@ -7,6 +7,7 @@ + -- cgit v1.2.3