You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

FileService.cs 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. using Microsoft.AspNetCore.Http;
  2. using Microsoft.Extensions.Configuration;
  3. using Microsoft.WindowsAzure.Storage;
  4. using Microsoft.WindowsAzure.Storage.Blob;
  5. namespace Diligent.WebAPI.Business.Services
  6. {
  7. public class FileService : IFileService
  8. {
  9. private readonly IConfiguration _configuration;
  10. private readonly DatabaseContext _context;
  11. public FileService(IConfiguration configuration, DatabaseContext context)
  12. {
  13. _configuration = configuration;
  14. _context = context;
  15. }
  16. public async Task<string> GetCV(string fileName)
  17. {
  18. await using MemoryStream memoryStream = new();
  19. var cloudBlockBlob = GetCloudBlockBlob(fileName);
  20. await cloudBlockBlob.DownloadToStreamAsync(memoryStream);
  21. Stream blobStream = cloudBlockBlob.OpenReadAsync().Result;
  22. return ConvertToBase64(blobStream);
  23. }
  24. public async Task UploadCV(string fileName,IFormFile file)
  25. {
  26. var cloudBlockBlob = GetCloudBlockBlob(fileName);
  27. await using var data = file.OpenReadStream();
  28. await cloudBlockBlob.UploadFromStreamAsync(data);
  29. }
  30. private CloudBlockBlob GetCloudBlockBlob(string fileName)
  31. {
  32. string blobstorageconnection = _configuration.GetValue<string>("BlobConnectionString");
  33. CloudStorageAccount cloudStorageAccount = CloudStorageAccount.Parse(blobstorageconnection);
  34. CloudBlobClient blobClient = cloudStorageAccount.CreateCloudBlobClient();
  35. CloudBlobContainer container = blobClient.GetContainerReference(
  36. _configuration.GetValue<string>("BlobContainerName"));
  37. return container.GetBlockBlobReference(fileName);
  38. }
  39. private static string ConvertToBase64(Stream stream)
  40. {
  41. byte[] bytes;
  42. using (var memoryStream = new MemoryStream())
  43. {
  44. stream.CopyTo(memoryStream);
  45. bytes = memoryStream.ToArray();
  46. }
  47. string base64 = Convert.ToBase64String(bytes);
  48. return base64;
  49. }
  50. }
  51. }