上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等

  • 上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等已关闭评论
  • 46 次浏览
  • A+
所属分类:.NET技术
摘要

上传附件判断word、excel、txt等文档中是否含有敏感词如身份证号,手机号等,其它检测如PDF,图片(OCR)等可以自行扩展。

上传附件判断word、excel、txt等文档中是否含有敏感词如身份证号,手机号等,其它检测如PDF,图片(OCR)等可以自行扩展。

互联网项目中,展示的数据中不能包含个人信息等敏感信息。判断word中是否包含手机号,word正文中是否包含身份证号等敏感信息,通过正则表达式判断匹配手机号,身份证号,以下做为参考。会出现碰撞错误,碰撞不准确等情况,不在本文范围。

开发语言C#,框架asp.net webform。由于传文件是做的判断,所以这里是判断数据流HttpPostedFile postedFile中的内容。通过load本地文件,本文不做过多介绍。

一、word校验身份证号,手机号

获取word中内容最初用的是npoi插件,office的插件导入导出以前用的比较多,npoi只获取docx文档文本,npoi获取doc后缀有问题,又找的Spire.Doc。可以都使用后者,笔者只简单测试了doc后缀,其它复杂情况没具体测试。有时间的推荐Spire,因为附件中pdf也是一个大项,刚好有对应的using Spire.Pdf;

using NPOI.XWPF.UserModel;
using Spire.Doc;
using Spire.Doc.Documents;

 public class WordToTextConvert  {      /// <summary>      /// docx提取成纯文本      /// </summary>      /// <param name="file"></param>      /// <returns></returns>      public static string ExtractTextFromWord(Stream wordFileStream,string fileExt)      {          using (wordFileStream)          {              XWPFDocument doc = new XWPFDocument(wordFileStream);               using (StringWriter writer = new StringWriter())              {                  string text = "";                  foreach (var para in doc.Paragraphs)                  {                      text += para.Text+" ";                  }                   foreach (XWPFTable table in doc.Tables)                  {                      foreach (XWPFTableRow row in table.Rows)                      {                          foreach (XWPFTableCell cell in row.GetTableCells())                          {                              text += cell.GetText() + " ";                          }                      }                      text += "rn";                  }                  return text;              }          }      }      /// <summary>      /// doc后缀      /// </summary>      /// <param name="wordFileStream"></param>      /// <param name="fileExt"></param>      /// <returns></returns>      public static string ExtractTextFromWordDoc(Stream wordFileStream, string fileExt)      {          Spire.Doc.Document doc = new Spire.Doc.Document(wordFileStream);          Spire.Doc.Table table = doc.Sections[0].Tables[0] as Table;          string text = doc.GetText()+" ";//获取word文档中的文本          //纯表格可以使用以下方法          //遍历表格内容          for (int i = 0; i < table.Rows.Count; i++)          {              var cellsindex = table.Rows[i].Cells.Count;              for (int j = 0; j < cellsindex; j++)              {                  TableCell cell = table.Rows[i].Cells[j];                  foreach (Paragraph paragraph in cell.Paragraphs)                  {                      text += paragraph.Text+" ";                  }              }               text += "rn";          }          return text;      }  }

二、EXCEL校验校验身份证号,手机号

npoi处理excel时要判断后缀,xls和xlsx使用的类不同

public class ExcelToTextConvert {     /// <summary>     /// 提取成纯文本     /// </summary>     /// <param name="file"></param>     /// <returns></returns>     public static string ExtractTextFromExcel(Stream excelFileStream,string fileExt)     {         using (excelFileStream)         {             string text = "";              IWorkbook workbook=null;             if (fileExt == "xls")             {                 workbook = new HSSFWorkbook(excelFileStream);             }             if (fileExt == "xlsx")             {                 workbook = new XSSFWorkbook(excelFileStream);             }             ISheet sheet = workbook.GetSheetAt(0);             if (sheet != null)             {                 foreach (IRow row in sheet)                 {                     foreach (ICell cell in row)                     {                         switch (cell.CellType)                         {                             case CellType.String:                                 text += cell.StringCellValue + " ";                                 break;                             case CellType.Numeric:                                 text += cell.NumericCellValue + " ";                                 break;                         }                     }                     text += "rn";                 }             }             return text;         }     } }

三、txt校验校验身份证号,手机号

获取文件流的内容,文本文件可以直接读取。方法如下:

if ("txt".Contains(fileExt)) {     // 确保文件不为null并且有数据     if (postedFile != null && postedFile.ContentLength > 0)     {         using (StreamReader reader = new StreamReader(postedFile.InputStream))         {             // 读取文件内容并返回             string readContent = reader.ReadToEnd();             bool hasMobile = ContainsMobileNumber(readContent);             if (hasMobile)             {                 return "{"status": 0, "msg": "内容中不可含有手机号!"}";             }             bool hasId = ContainsIdNumber(readContent);             if (hasId)             {                 return "{"status": 0, "msg": "内容中不可含有身份证号!"}";             }         }     } }

 四、正则校验字符串中是否包含身份证号,手机号等

public static bool ContainsMobileNumber(string text) {     // 中国大陆手机号码正则表达式     string pattern = @"1[3-9]d{9}";     return Regex.IsMatch(text, pattern); }  public static bool ContainsIdNumber(string text) {     // 中国大陆身份证号正则表达式     string pattern = @"[1-9]d{5}(18|19|20)?d{2}(0[1-9]|1[0-2])(0[1-9]|[12]d|3[01])d{3}(d|[Xx])";     return Regex.IsMatch(text, pattern); }

五、读取pdf方法,未做项目验证,请自行搜索相关方法

供参考:读取显示PDF需要借助PDF库,国内Spire.PDF可以读取PDF内容,包括文本,图片以及表格,你可以通过NuGet搜索安装

上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等上传文件附件时判断word、excel、txt等是否含有敏感词如身份证号,手机号等

  1 using Spire.Pdf;   2 using Spire.Pdf.Texts;   3 using System.IO;   4    5 using System.Text;   6    7 namespace ExtractText   8    9 {  10   11 internal class Program  12   13 {  14   15 static void Main(string[] args)  16   17 {  18   19 //创建一个 PdfDocument 对象  20   21 PdfDocument doc = new PdfDocument();  22 //加载PDF文件  23   24 doc.LoadFromFile("AI数字人.pdf");  25   26 StringBuilder sb = new StringBuilder();  27   28 foreach (PdfPageBase page in doc.Pages)  29   30 {  31   32 //创建一个PdfTextExtractot 对象  33   34 PdfTextExtractor textExtractor = new PdfTextExtractor(page);  35   36 //创建一个 PdfTextExtractOptions 对象  37   38 PdfTextExtractOptions extractOptions = new PdfTextExtractOptions();  39   40 //将 isExtractAllText 设置为true  41   42 extractOptions.IsExtractAllText = true;  43   44 //从页面中提取文本  45   46 sb.AppendLine(textExtractor.ExtractText(extractOptions));  47   48 }  49   50 //将提取的文本写入 TXT 文件  51   52 File.WriteAllText("提取指定页面文本.txt", sb.ToString());  53   54 }  55   56 }  57   58 }  59   60 读取表格内容:  61   62 using Spire.Pdf;  63   64 using Spire.Pdf.Utilities;  65   66 using System.IO;  67   68 using System.Text;  69   70 namespace ExtractTable{  71 class Program  72 {  73 static void Main(string[] args)  74 {  75 //实例化PdfDocument类的对象  76 PdfDocument pdf = new PdfDocument();  77 //加载PDF文档  78 pdf.LoadFromFile("sample.pdf");  79 //创建StringBuilder类的对象  80 StringBuilder builder = new StringBuilder();  81 //实例化PdfTableExtractor类的对象  82 PdfTableExtractor extractor = new PdfTableExtractor(pdf);  83 //声明PdfTable类的表格数组  84 PdfTable[] tableLists;  85 //遍历PDF页面  86 for (int pageIndex = 0; pageIndex < pdf.Pages.Count; pageIndex++)  87 {  88 //从页面提取表格  89 tableLists = extractor.ExtractTable(pageIndex);  90 //判断表格列表是否为空  91 if (tableLists != null && tableLists.Length > 0)  92 {  93 //遍历表格  94 foreach (PdfTable table in tableLists)  95 {  96 //获取表格中的行和列数  97 int row = table.GetRowCount();  98 int column = table.GetColumnCount();  99 //遍历表格行和列 100 for (int i = 0; i < row; i++) 101 { 102 for (int j = 0; j < column; j++) 103 { 104 //获取行和列中的文本 105 string text = table.GetText(i, j); 106 //写入文本到StringBuilder容器 107 builder.Append(text + " "); 108 } 109 builder.Append("rn"); 110 } 111 } 112 } 113 } 114 //保存提取的表格内容为.txt文档 115 File.WriteAllText("ExtractedTable.txt", builder.ToString()); 116 } 117 } 118  119 }

读取PDF的内容,文本、表格、图片

 

总结:尽一切合理努力保护用户个人信息, 并对个人信息进行保护。为防止用户个人信息在意外的、未经授权的情况下泄漏。

压缩包内容校验基本方法同上,先解压缩,再逐文件处理。本文直接判断有敏感词,不让上传,也可以通过正则把信息替换成****后再转存,这里不再展开。

如有专门的更好用的插件请留言告知讨论,避免重复造轮子。