aboutsummaryrefslogtreecommitdiff
path: root/ExamTemplate/Services/CloudinaryService.cs
blob: 03b72657fcd1d125df9e5f5b1f5f16b29b58d165 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
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<List<string>> UploadFilesToCloud(List<IFormFile> formFiles)
		{
			List<string> 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;
		}
	}
}