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.

Uploader.cs 2.7KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.IO;
  6. using Teknik.Configuration;
  7. using Teknik.Models;
  8. namespace Teknik.Areas.Upload
  9. {
  10. public static class Uploader
  11. {
  12. public static Models.Upload SaveFile(byte[] file, string contentType, int contentLength)
  13. {
  14. return SaveFile(file, contentType, contentLength, null, null, 256, 128);
  15. }
  16. public static Models.Upload SaveFile(byte[] file, string contentType, int contentLength, string iv)
  17. {
  18. return SaveFile(file, contentType, contentLength, iv, null, 256, 128);
  19. }
  20. public static Models.Upload SaveFile(byte[] file, string contentType, int contentLength, string iv, string key)
  21. {
  22. return SaveFile(file, contentType, contentLength, iv, key, 256, 128);
  23. }
  24. public static Models.Upload SaveFile(byte[] file, string contentType, int contentLength, string iv, string key, int keySize, int blockSize)
  25. {
  26. Config config = Config.Load();
  27. TeknikEntities db = new TeknikEntities();
  28. if (!Directory.Exists(config.UploadConfig.UploadDirectory))
  29. {
  30. Directory.CreateDirectory(config.UploadConfig.UploadDirectory);
  31. }
  32. // Generate a unique file name that does not currently exist
  33. string fileName = Utility.GenerateUniqueFileName(config.UploadConfig.UploadDirectory, config.UploadConfig.FileExtension, 10);
  34. // once we have the filename, lets save the file
  35. File.WriteAllBytes(fileName, file);
  36. // Generate a unique url
  37. string extension = (config.UploadConfig.IncludeExtension) ? Utility.GetDefaultExtension(contentType) : string.Empty;
  38. string url = Utility.RandomString(config.UploadConfig.UrlLength) + extension;
  39. while (db.Uploads.Where(u => u.Url == url).FirstOrDefault() != null)
  40. {
  41. url = Utility.RandomString(config.UploadConfig.UrlLength) + extension;
  42. }
  43. // Now we need to update the database with the new upload information
  44. Models.Upload upload = db.Uploads.Create();
  45. upload.DateUploaded = DateTime.Now;
  46. upload.Url = url;
  47. upload.FileName = fileName;
  48. upload.ContentType = (!string.IsNullOrEmpty(contentType)) ? contentType : "application/octet-stream";
  49. upload.ContentLength = contentLength;
  50. upload.Key = key;
  51. upload.IV = iv;
  52. upload.KeySize = keySize;
  53. upload.BlockSize = blockSize;
  54. db.Uploads.Add(upload);
  55. db.SaveChanges();
  56. return upload;
  57. }
  58. }
  59. }