人民医院API

FileHelper.cs 2.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Web;
  8. namespace RMYY_CallCenter_Api.Utility
  9. {
  10. public static class FileHelper
  11. {
  12. /// <summary>
  13. /// 上传文件
  14. /// </summary>
  15. /// <param name="hpFile">文件</param>
  16. /// <param name="path">路径</param>
  17. /// <returns></returns>
  18. public static string Upload(HttpPostedFileBase hpFile, string path)
  19. {
  20. path = HttpContext.Current.Server.MapPath("..") + path;
  21. string newName = "(" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + ")" + hpFile.FileName;
  22. int iLen = hpFile.ContentLength;
  23. if (!Directory.Exists(path)) Directory.CreateDirectory(path);
  24. byte[] bData = new byte[iLen];
  25. hpFile.InputStream.Read(bData, 0, iLen);
  26. FileStream newFile = new FileStream(path + newName, FileMode.Create);
  27. newFile.Write(bData, 0, bData.Length);
  28. newFile.Flush();
  29. return newName;
  30. }
  31. /// <summary>
  32. /// 根据地址获取文件扩展名
  33. /// </summary>
  34. /// <param name="path"></param>
  35. /// <returns></returns>
  36. public static string GetExt(string path)
  37. {
  38. return Path.GetExtension(path);
  39. }
  40. /// <summary>
  41. /// 获取文件MD5值
  42. /// </summary>
  43. /// <param name="fileName">文件绝对路径</param>
  44. /// <returns>MD5值</returns>
  45. public static string GetFileMD5(string fileName)
  46. {
  47. try
  48. {
  49. FileStream file = new FileStream(fileName, FileMode.Open);
  50. System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
  51. byte[] retVal = md5.ComputeHash(file);
  52. file.Close();
  53. StringBuilder sb = new StringBuilder();
  54. for (int i = 0; i < retVal.Length; i++)
  55. {
  56. sb.Append(retVal[i].ToString("x2"));
  57. }
  58. return sb.ToString();
  59. }
  60. catch
  61. {
  62. return null;
  63. }
  64. }
  65. }
  66. }