File size: 5,279 Bytes
fc06b79 | 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 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 | using Microsoft.AspNetCore.Http;
using System;
using System.IO;
using System.Threading.Tasks;
namespace ContactManagementAPI.Services
{
public class FileUploadService
{
private readonly IWebHostEnvironment _environment;
private readonly IConfiguration _configuration;
private const long MAX_PHOTO_SIZE = 5242880; // 5MB
private const long MAX_DOCUMENT_SIZE = 10485760; // 10MB
public FileUploadService(IWebHostEnvironment environment, IConfiguration configuration)
{
_environment = environment;
_configuration = configuration;
}
private string GetUploadsRoot()
{
var uploadsRoot = Environment.GetEnvironmentVariable("UPLOADS_ROOT");
if (!string.IsNullOrWhiteSpace(uploadsRoot))
{
Directory.CreateDirectory(uploadsRoot);
return uploadsRoot;
}
return Path.Combine(_environment.WebRootPath, "uploads");
}
public async Task<(bool Success, string FilePath, string ErrorMessage)> UploadPhotoAsync(IFormFile file, int contactId)
{
try
{
if (file == null || file.Length == 0)
return (false, "", "No file selected");
if (file.Length > MAX_PHOTO_SIZE)
return (false, "", "Photo size exceeds maximum limit of 5MB");
var allowedExtensions = _configuration.GetSection("FileUpload:AllowedPhotoExtensions").Get<string[]>();
var fileExtension = Path.GetExtension(file.FileName).ToLower();
if (!allowedExtensions.Contains(fileExtension))
return (false, "", "Invalid file format. Allowed formats: JPG, PNG, GIF, BMP");
var uploadPath = Path.Combine(GetUploadsRoot(), "photos");
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
var fileName = $"{contactId}_{DateTime.Now.Ticks}{fileExtension}";
var filePath = Path.Combine(uploadPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return (true, $"/uploads/photos/{fileName}", "");
}
catch (Exception ex)
{
return (false, "", $"Error uploading file: {ex.Message}");
}
}
public async Task<(bool Success, string FilePath, string ErrorMessage)> UploadDocumentAsync(IFormFile file, int contactId)
{
try
{
if (file == null || file.Length == 0)
return (false, "", "No file selected");
if (file.Length > MAX_DOCUMENT_SIZE)
return (false, "", "Document size exceeds maximum limit of 10MB");
var allowedExtensions = _configuration.GetSection("FileUpload:AllowedDocumentExtensions").Get<string[]>();
var fileExtension = Path.GetExtension(file.FileName).ToLower();
if (!allowedExtensions.Contains(fileExtension))
return (false, "", "Invalid file format");
var uploadPath = Path.Combine(GetUploadsRoot(), "documents");
if (!Directory.Exists(uploadPath))
Directory.CreateDirectory(uploadPath);
var fileName = $"{contactId}_{DateTime.Now.Ticks}{fileExtension}";
var filePath = Path.Combine(uploadPath, fileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return (true, $"/uploads/documents/{fileName}", "");
}
catch (Exception ex)
{
return (false, "", $"Error uploading file: {ex.Message}");
}
}
public bool DeleteFile(string filePath)
{
try
{
var trimmed = (filePath ?? string.Empty).Trim();
if (string.IsNullOrWhiteSpace(trimmed))
{
return false;
}
var normalized = trimmed.StartsWith("/") ? trimmed : "/" + trimmed;
var uploadsRoot = GetUploadsRoot();
string fullPath;
if (normalized.StartsWith("/uploads/", StringComparison.OrdinalIgnoreCase))
{
var relative = normalized.Substring("/uploads/".Length).Replace('/', Path.DirectorySeparatorChar);
fullPath = Path.Combine(uploadsRoot, relative);
}
else
{
fullPath = Path.Combine(_environment.WebRootPath, normalized.TrimStart('/').Replace('/', Path.DirectorySeparatorChar));
}
if (File.Exists(fullPath))
{
File.Delete(fullPath);
return true;
}
return false;
}
catch
{
return false;
}
}
}
}
|