The next generation of the Teknik Services. Written in ASP.NET. https://www.teknik.io/
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.

UploadController.cs 29KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588
  1. using nClam;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using Teknik.Areas.Upload.ViewModels;
  7. using Teknik.Areas.Users.Utility;
  8. using Teknik.Controllers;
  9. using Teknik.Filters;
  10. using Teknik.Utilities;
  11. using Teknik.Models;
  12. using Teknik.Attributes;
  13. using System.Text;
  14. using Teknik.Utilities.Cryptography;
  15. using Teknik.Data;
  16. using Teknik.Configuration;
  17. using Microsoft.Extensions.Logging;
  18. using Microsoft.AspNetCore.Mvc;
  19. using Microsoft.AspNetCore.Authorization;
  20. using System.Threading.Tasks;
  21. using Microsoft.EntityFrameworkCore;
  22. using Microsoft.AspNetCore.Http;
  23. using Teknik.Logging;
  24. using Teknik.Areas.Users.Models;
  25. using Teknik.ContentScanningService;
  26. namespace Teknik.Areas.Upload.Controllers
  27. {
  28. [Authorize]
  29. [Area("Upload")]
  30. public class UploadController : DefaultController
  31. {
  32. public UploadController(ILogger<Logger> logger, Config config, TeknikEntities dbContext) : base(logger, config, dbContext) { }
  33. [HttpGet]
  34. [TrackPageView]
  35. public async Task<IActionResult> Index()
  36. {
  37. ViewBag.Title = "Upload Files";
  38. UploadViewModel model = new UploadViewModel();
  39. model.CurrentSub = Subdomain;
  40. model.Encrypt = false;
  41. model.ExpirationLength = 1;
  42. model.ExpirationUnit = ExpirationUnit.Days;
  43. model.MaxUploadSize = _config.UploadConfig.MaxUploadSize;
  44. if (User.Identity.IsAuthenticated)
  45. {
  46. User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  47. if (user != null)
  48. {
  49. model.Encrypt = user.UploadSettings.Encrypt;
  50. model.ExpirationLength = user.UploadSettings.ExpirationLength;
  51. model.ExpirationUnit = user.UploadSettings.ExpirationUnit;
  52. model.Vaults = user.Vaults.ToList();
  53. model.CurrentTotalSize = user.Uploads.Sum(u => u.ContentLength);
  54. model.MaxUploadSize = _config.UploadConfig.MaxUploadSizeBasic;
  55. model.MaxTotalSize = _config.UploadConfig.MaxTotalSizeBasic;
  56. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  57. if (userInfo.AccountType == AccountType.Premium)
  58. {
  59. model.MaxUploadSize = _config.UploadConfig.MaxUploadSizePremium;
  60. model.MaxTotalSize = _config.UploadConfig.MaxTotalSizePremium;
  61. }
  62. if (user.UploadSettings.MaxUploadStorage != null)
  63. model.MaxTotalSize = user.UploadSettings.MaxUploadStorage.Value;
  64. if (model.CurrentTotalSize >= model.MaxTotalSize)
  65. {
  66. model.Error = true;
  67. model.ErrorMessage = string.Format("Account storage limit exceeded: {0} / {1}", StringHelper.GetBytesReadable(model.CurrentTotalSize), StringHelper.GetBytesReadable(model.MaxTotalSize));
  68. }
  69. }
  70. }
  71. return View(model);
  72. }
  73. [HttpPost]
  74. [DisableRequestSizeLimit]
  75. public async Task<IActionResult> Upload([FromForm] UploadFileViewModel uploadFile)
  76. {
  77. try
  78. {
  79. if (_config.UploadConfig.UploadEnabled)
  80. {
  81. long maxUploadSize = _config.UploadConfig.MaxUploadSize;
  82. if (User.Identity.IsAuthenticated)
  83. {
  84. maxUploadSize = _config.UploadConfig.MaxUploadSizeBasic;
  85. long maxTotalSize = _config.UploadConfig.MaxTotalSizeBasic;
  86. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  87. if (userInfo.AccountType == AccountType.Premium)
  88. {
  89. maxUploadSize = _config.UploadConfig.MaxUploadSizePremium;
  90. maxTotalSize = _config.UploadConfig.MaxTotalSizePremium;
  91. }
  92. // Check account total limits
  93. var user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  94. if (user.UploadSettings.MaxUploadStorage != null)
  95. maxTotalSize = user.UploadSettings.MaxUploadStorage.Value;
  96. var userUploadSize = user.Uploads.Sum(u => u.ContentLength);
  97. if (userUploadSize + uploadFile.file.Length > maxTotalSize)
  98. {
  99. return Json(new { error = new { message = string.Format("Account storage limit exceeded. {0} / {1}", StringHelper.GetBytesReadable(userUploadSize + uploadFile.file.Length), StringHelper.GetBytesReadable(maxTotalSize)) } });
  100. }
  101. }
  102. else
  103. {
  104. // Non-logged in users are defaulted to 1 day expiration
  105. uploadFile.options.ExpirationUnit = ExpirationUnit.Days;
  106. uploadFile.options.ExpirationLength = 1;
  107. }
  108. if (uploadFile.file.Length <= maxUploadSize)
  109. {
  110. // convert file to bytes
  111. long contentLength = uploadFile.file.Length;
  112. using (Stream fs = uploadFile.file.OpenReadStream())
  113. {
  114. ScanResult scanResult = null;
  115. // Scan the file to detect a virus
  116. if (_config.UploadConfig.ClamConfig.Enabled)
  117. {
  118. var clamScanner = new ClamScanner(_config);
  119. scanResult = await clamScanner.ScanFile(fs);
  120. }
  121. // Scan the files against an endpoint based on hash
  122. if (_config.UploadConfig.HashScanConfig.Enabled && (scanResult == null || scanResult.ResultType == ScanResultType.Clean))
  123. {
  124. var hashScanner = new HashScanner(_config);
  125. scanResult = await hashScanner.ScanFile(fs);
  126. }
  127. switch (scanResult?.ResultType)
  128. {
  129. case ScanResultType.Clean:
  130. break;
  131. case ScanResultType.VirusDetected:
  132. return Json(new { error = new { message = string.Format("Virus Detected: {0}. As per our <a href=\"{1}\">Terms of Service</a>, Viruses are not permited.", scanResult.RawResult, Url.SubRouteUrl("tos", "TOS.Index")) } });
  133. case ScanResultType.ChildPornography:
  134. return Json(new { error = new { message = string.Format("Child Pornography Detected: As per our <a href=\"{0}\">Terms of Service</a>, Child Pornography is not permited.", Url.SubRouteUrl("tos", "TOS.Index")) } });
  135. case ScanResultType.Error:
  136. return Json(new { error = new { message = string.Format("Error scanning the file upload. {0}", scanResult.RawResult) } });
  137. case ScanResultType.Unknown:
  138. return Json(new { error = new { message = string.Format("Unknown result while scanning the file upload. {0}", scanResult.RawResult) } });
  139. }
  140. // Check content type restrictions (Only for encrypting server side
  141. if (!uploadFile.options.Encrypt)
  142. {
  143. if (_config.UploadConfig.RestrictedContentTypes.Contains(uploadFile.fileType) || _config.UploadConfig.RestrictedExtensions.Contains(uploadFile.fileExt))
  144. {
  145. return Json(new { error = new { message = "File Type Not Allowed" } });
  146. }
  147. }
  148. Models.Upload upload = UploadHelper.SaveFile(_dbContext,
  149. _config,
  150. fs,
  151. uploadFile.fileType,
  152. contentLength,
  153. !uploadFile.options.Encrypt,
  154. uploadFile.options.ExpirationUnit,
  155. uploadFile.options.ExpirationLength,
  156. uploadFile.fileExt,
  157. uploadFile.iv, null,
  158. uploadFile.keySize,
  159. uploadFile.blockSize);
  160. if (upload != null)
  161. {
  162. if (User.Identity.IsAuthenticated)
  163. {
  164. Users.Models.User user = UserHelper.GetUser(_dbContext, User.Identity.Name);
  165. if (user != null)
  166. {
  167. upload.UserId = user.UserId;
  168. _dbContext.Entry(upload).State = EntityState.Modified;
  169. _dbContext.SaveChanges();
  170. }
  171. }
  172. return Json(new
  173. {
  174. result = new
  175. {
  176. name = upload.Url,
  177. url = Url.SubRouteUrl("u", "Upload.Download", new { file = upload.Url }),
  178. contentType = upload.ContentType,
  179. contentLength = StringHelper.GetBytesReadable(upload.ContentLength),
  180. contentLengthRaw = upload.ContentLength,
  181. deleteUrl = Url.SubRouteUrl("u", "Upload.DeleteByKey", new { file = upload.Url, key = upload.DeleteKey }),
  182. expirationUnit = uploadFile.options.ExpirationUnit.ToString(),
  183. expirationLength = uploadFile.options.ExpirationLength
  184. }
  185. });
  186. }
  187. }
  188. return Json(new { error = new { message = "Unable to upload file" } });
  189. }
  190. else
  191. {
  192. return Json(new { error = new { message = "File Too Large. Max file size is " + StringHelper.GetBytesReadable(maxUploadSize) } });
  193. }
  194. }
  195. return Json(new { error = new { message = "Uploads are disabled" } });
  196. }
  197. catch (Exception ex)
  198. {
  199. return Json(new { error = new { message = "Exception while uploading file: " + ex.GetFullMessage(true) } });
  200. }
  201. }
  202. [HttpGet]
  203. [AllowAnonymous]
  204. [TrackPageView]
  205. [ResponseCache(Duration = 31536000, Location = ResponseCacheLocation.Any)]
  206. public async Task<IActionResult> Download(string file)
  207. {
  208. if (_config.UploadConfig.DownloadEnabled)
  209. {
  210. ViewBag.Title = "Download " + file;
  211. string fileName = string.Empty;
  212. string url = string.Empty;
  213. string key = string.Empty;
  214. string iv = string.Empty;
  215. string contentType = string.Empty;
  216. long contentLength = 0;
  217. bool premiumAccount = false;
  218. DateTime dateUploaded = new DateTime();
  219. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  220. if (upload != null)
  221. {
  222. // Check Expiration
  223. if (UploadHelper.CheckExpiration(upload))
  224. {
  225. DeleteFile(upload);
  226. return new StatusCodeResult(StatusCodes.Status404NotFound);
  227. }
  228. upload.Downloads += 1;
  229. _dbContext.Entry(upload).State = EntityState.Modified;
  230. _dbContext.SaveChanges();
  231. fileName = upload.FileName;
  232. url = upload.Url;
  233. key = upload.Key;
  234. iv = upload.IV;
  235. contentType = upload.ContentType;
  236. contentLength = upload.ContentLength;
  237. dateUploaded = upload.DateUploaded;
  238. if (User.Identity.IsAuthenticated)
  239. {
  240. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, User.Identity.Name);
  241. premiumAccount = userInfo.AccountType == AccountType.Premium;
  242. }
  243. if (!premiumAccount && upload.User != null)
  244. {
  245. IdentityUserInfo userInfo = await IdentityHelper.GetIdentityUserInfo(_config, upload.User.Username);
  246. premiumAccount = userInfo.AccountType == AccountType.Premium;
  247. }
  248. }
  249. else
  250. {
  251. return new StatusCodeResult(StatusCodes.Status404NotFound);
  252. }
  253. // We don't have the key, so we need to decrypt it client side
  254. if (string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  255. {
  256. DownloadViewModel model = new DownloadViewModel();
  257. model.CurrentSub = Subdomain;
  258. model.FileName = file;
  259. model.ContentType = contentType;
  260. model.ContentLength = contentLength;
  261. model.IV = iv;
  262. model.Decrypt = true;
  263. return View(model);
  264. }
  265. else if (!premiumAccount && _config.UploadConfig.MaxDownloadSize < contentLength)
  266. {
  267. // We want to force them to the dl page due to them being over the max download size for embedded content
  268. DownloadViewModel model = new DownloadViewModel();
  269. model.CurrentSub = Subdomain;
  270. model.FileName = file;
  271. model.ContentType = contentType;
  272. model.ContentLength = contentLength;
  273. model.Decrypt = false;
  274. return View(model);
  275. }
  276. else // We have the key, so that means server side decryption
  277. {
  278. // Check for the cache
  279. bool isCached = false;
  280. string modifiedSince = Request.Headers["If-Modified-Since"];
  281. if (!string.IsNullOrEmpty(modifiedSince))
  282. {
  283. DateTime modTime = new DateTime();
  284. bool parsed = DateTime.TryParse(modifiedSince, out modTime);
  285. if (parsed)
  286. {
  287. if ((modTime - dateUploaded).TotalSeconds <= 1)
  288. {
  289. isCached = true;
  290. }
  291. }
  292. }
  293. if (isCached)
  294. {
  295. return new StatusCodeResult(StatusCodes.Status304NotModified);
  296. }
  297. else
  298. {
  299. string subDir = fileName[0].ToString();
  300. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, fileName);
  301. long startByte = 0;
  302. long endByte = contentLength - 1;
  303. long length = contentLength;
  304. if (System.IO.File.Exists(filePath))
  305. {
  306. #region Range Calculation
  307. // Are they downloading it by range?
  308. bool byRange = !string.IsNullOrEmpty(Request.Headers["Range"]); // We do not support ranges
  309. // check to see if we need to pass a specified range
  310. if (byRange)
  311. {
  312. long anotherStart = startByte;
  313. long anotherEnd = endByte;
  314. string[] arr_split = Request.Headers["Range"].ToString().Split(new char[] { '=' });
  315. string range = arr_split[1];
  316. // Make sure the client hasn't sent us a multibyte range
  317. if (range.IndexOf(",") > -1)
  318. {
  319. // (?) Shoud this be issued here, or should the first
  320. // range be used? Or should the header be ignored and
  321. // we output the whole content?
  322. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  323. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  324. }
  325. // If the range starts with an '-' we start from the beginning
  326. // If not, we forward the file pointer
  327. // And make sure to get the end byte if spesified
  328. if (range.StartsWith("-"))
  329. {
  330. // The n-number of the last bytes is requested
  331. anotherStart = startByte - Convert.ToInt64(range.Substring(1));
  332. }
  333. else
  334. {
  335. arr_split = range.Split(new char[] { '-' });
  336. anotherStart = Convert.ToInt64(arr_split[0]);
  337. long temp = 0;
  338. anotherEnd = (arr_split.Length > 1 && Int64.TryParse(arr_split[1].ToString(), out temp)) ? Convert.ToInt64(arr_split[1]) : contentLength;
  339. }
  340. /* Check the range and make sure it's treated according to the specs.
  341. * http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
  342. */
  343. // End bytes can not be larger than $end.
  344. anotherEnd = (anotherEnd > endByte) ? endByte : anotherEnd;
  345. // Validate the requested range and return an error if it's not correct.
  346. if (anotherStart > anotherEnd || anotherStart > contentLength - 1 || anotherEnd >= contentLength)
  347. {
  348. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  349. return new StatusCodeResult(StatusCodes.Status416RequestedRangeNotSatisfiable);
  350. }
  351. startByte = anotherStart;
  352. endByte = anotherEnd;
  353. length = endByte - startByte + 1; // Calculate new content length
  354. // Ranges are response of 206
  355. Response.StatusCode = 206;
  356. }
  357. #endregion
  358. // Set Last Modified
  359. Response.GetTypedHeaders().LastModified = dateUploaded;
  360. // We accept ranges
  361. Response.Headers.Add("Accept-Ranges", "0-" + contentLength);
  362. // Notify the client the byte range we'll be outputting
  363. Response.Headers.Add("Content-Range", "bytes " + startByte + "-" + endByte + "/" + contentLength);
  364. // Notify the client the content length we'll be outputting
  365. Response.Headers.Add("Content-Length", length.ToString());
  366. // Set the content type of this response
  367. Response.Headers.Add("Content-Type", contentType);
  368. // Create content disposition
  369. var cd = new System.Net.Mime.ContentDisposition
  370. {
  371. FileName = url,
  372. Inline = true
  373. };
  374. Response.Headers.Add("Content-Disposition", cd.ToString());
  375. // Read in the file
  376. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  377. // Reset file stream to starting position (or start of range)
  378. fs.Seek(startByte, SeekOrigin.Begin);
  379. try
  380. {
  381. // If the IV is set, and Key is set, then decrypt it while sending
  382. if (!string.IsNullOrEmpty(key) && !string.IsNullOrEmpty(iv))
  383. {
  384. byte[] keyBytes = Encoding.UTF8.GetBytes(key);
  385. byte[] ivBytes = Encoding.UTF8.GetBytes(iv);
  386. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)length, _config.UploadConfig.ChunkSize), false);
  387. }
  388. else // Otherwise just send it
  389. {
  390. // Send the file
  391. return new BufferedFileStreamResult(contentType, async (response) => await ResponseHelper.StreamToOutput(response, true, fs, (int)length, _config.UploadConfig.ChunkSize), false);
  392. }
  393. }
  394. catch (Exception ex)
  395. {
  396. _logger.LogWarning(ex, "Error in Download: {url}", new { url });
  397. }
  398. }
  399. }
  400. return new StatusCodeResult(StatusCodes.Status404NotFound);
  401. }
  402. }
  403. return new StatusCodeResult(StatusCodes.Status403Forbidden);
  404. }
  405. [HttpPost]
  406. [AllowAnonymous]
  407. public IActionResult DownloadData(string file, bool decrypt)
  408. {
  409. if (_config.UploadConfig.DownloadEnabled)
  410. {
  411. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  412. if (upload != null)
  413. {
  414. // Check Expiration
  415. if (UploadHelper.CheckExpiration(upload))
  416. {
  417. DeleteFile(upload);
  418. return Json(new { error = new { message = "File Does Not Exist" } });
  419. }
  420. string subDir = upload.FileName[0].ToString();
  421. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  422. if (System.IO.File.Exists(filePath))
  423. {
  424. // Notify the client the content length we'll be outputting
  425. Response.Headers.Add("Content-Length", upload.ContentLength.ToString());
  426. // Create content disposition
  427. var cd = new System.Net.Mime.ContentDisposition
  428. {
  429. FileName = upload.Url,
  430. Inline = true
  431. };
  432. // Set the content type of this response
  433. Response.Headers.Add("Content-Type", upload.ContentType);
  434. Response.Headers.Add("Content-Disposition", cd.ToString());
  435. // Read in the file
  436. FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read);
  437. // If the IV is set, and Key is set, then decrypt it while sending
  438. if (decrypt && !string.IsNullOrEmpty(upload.Key) && !string.IsNullOrEmpty(upload.IV))
  439. {
  440. byte[] keyBytes = Encoding.UTF8.GetBytes(upload.Key);
  441. byte[] ivBytes = Encoding.UTF8.GetBytes(upload.IV);
  442. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, new AesCounterStream(fs, false, keyBytes, ivBytes), (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  443. }
  444. else // Otherwise just send it
  445. {
  446. // Send the file
  447. return new BufferedFileStreamResult(upload.ContentType, (response) => ResponseHelper.StreamToOutput(response, true, fs, (int)upload.ContentLength, _config.UploadConfig.ChunkSize), false);
  448. }
  449. }
  450. }
  451. return Json(new { error = new { message = "File Does Not Exist" } });
  452. }
  453. return Json(new { error = new { message = "Downloads are disabled" } });
  454. }
  455. [HttpGet]
  456. [AllowAnonymous]
  457. public IActionResult DeleteByKey(string file, string key)
  458. {
  459. ViewBag.Title = "File Delete | " + file ;
  460. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  461. if (upload != null)
  462. {
  463. DeleteViewModel model = new DeleteViewModel();
  464. model.File = file;
  465. if (!string.IsNullOrEmpty(upload.DeleteKey) && upload.DeleteKey == key)
  466. {
  467. DeleteFile(upload);
  468. model.Deleted = true;
  469. }
  470. else
  471. {
  472. model.Deleted = false;
  473. }
  474. return View(model);
  475. }
  476. return new StatusCodeResult(StatusCodes.Status404NotFound);
  477. }
  478. [HttpPost]
  479. public IActionResult GenerateDeleteKey(string file)
  480. {
  481. Models.Upload upload = _dbContext.Uploads.Where(up => up.Url == file).FirstOrDefault();
  482. if (upload != null)
  483. {
  484. if (upload.User.Username == User.Identity.Name)
  485. {
  486. string delKey = StringHelper.RandomString(_config.UploadConfig.DeleteKeyLength);
  487. upload.DeleteKey = delKey;
  488. _dbContext.Entry(upload).State = EntityState.Modified;
  489. _dbContext.SaveChanges();
  490. return Json(new { result = new { url = Url.SubRouteUrl("u", "Upload.DeleteByKey", new { file = file, key = delKey }) } });
  491. }
  492. return Json(new { error = new { message = "You do not own this upload" } });
  493. }
  494. return Json(new { error = new { message = "Invalid URL" } });
  495. }
  496. [HttpPost]
  497. [HttpOptions]
  498. public IActionResult Delete(string id)
  499. {
  500. Models.Upload foundUpload = _dbContext.Uploads.Where(u => u.Url == id).FirstOrDefault();
  501. if (foundUpload != null)
  502. {
  503. if (foundUpload.User.Username == User.Identity.Name)
  504. {
  505. DeleteFile(foundUpload);
  506. return Json(new { result = true });
  507. }
  508. return Json(new { error = new { message = "You do not have permission to edit this Paste" } });
  509. }
  510. return Json(new { error = new { message = "This Upload does not exist" } });
  511. }
  512. private void DeleteFile(Models.Upload upload)
  513. {
  514. string subDir = upload.FileName[0].ToString();
  515. string filePath = Path.Combine(_config.UploadConfig.UploadDirectory, subDir, upload.FileName);
  516. // Delete the File
  517. if (System.IO.File.Exists(filePath))
  518. {
  519. try
  520. {
  521. System.IO.File.Delete(filePath);
  522. }
  523. catch (Exception ex)
  524. {
  525. _logger.LogError(ex, "Unable to delete file: {0}", upload.FileName);
  526. }
  527. }
  528. // Delete from the DB
  529. _dbContext.Uploads.Remove(upload);
  530. _dbContext.SaveChanges();
  531. }
  532. }
  533. }