C# File upload with safe filename


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. public String Upload()
  2. {
  3. var fileName = Path.GetFileNameWithoutExtension(Request.Files[0].FileName);
  4. string extension = System.IO.Path.GetExtension(Request.Files[0].FileName);
  5.  
  6. if (Request.Files.Count > 0 && extension == ".pdf")
  7. {
  8. Request.Files[0].SaveAs(Server.MapPath("/Content/userfiles/wholesale/") + FilenameFromTitle(fileName, extension));
  9. return "1";
  10. }
  11.  
  12. else
  13. {
  14. return "0";
  15. }
  16. }
  17.  
  18. public static string FilenameFromTitle(string name, string extension)
  19. {
  20. DateTime time = DateTime.Now;
  21. string format = "MMddyy_HHmmss";
  22. //Console.WriteLine(time.ToString(format));
  23.  
  24. // first trim the raw string
  25. string safe = name.Trim();
  26.  
  27. // replace spaces with hyphens
  28. safe = safe.Replace(" ", "-").ToLower();
  29.  
  30. // replace any 'double spaces' with singles
  31. if(safe.IndexOf("--") > -1)
  32. while(safe.IndexOf("--") > -1)
  33. safe = safe.Replace("--", "-");
  34.  
  35. // trim out illegal characters
  36. safe = Regex.Replace(safe, "[^a-z0-9\\-]", "");
  37.  
  38.  
  39. // trim the length
  40. if(safe.Length > 50)
  41. safe = safe.Substring(0, 49);
  42.  
  43. // clean the beginning and end of the filename
  44. char[] replace = {'-','.'};
  45. safe = safe.TrimStart(replace);
  46. safe = safe.TrimEnd(replace);
  47. safe = safe.ToLower() + "_" + time.ToString(format) + extension;
  48. //safe = safe.ToLower() + extension;
  49.  
  50. return safe;
  51. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.