18910140161

文件的上传/下载+在线游览(转化html)--不需要在线插件//自己写的小方法

顺晟科技

2022-09-15 19:23:56

271

文件的上传/下载+在线游览(转化html)--不需要在线插件//自己写的小方法

 

 

  1     /// <summary>
  2     /// 文件上传下载帮助类
  3     /// </summary>
  4     public static class FileHelper
  5     {
  6 
  7         /// <summary>
  8         /// 附件上传
  9         /// </summary>
 10         /// <param name="file">上传文件</param>
 11         /// <param name="uploadPath">上传位置</param>
 12         /// <returns></returns>
 13         public static string UploadFile(IFormFile file,string uploadPath)
 14         {
 15             try
 16             {
 17                 if (!Directory.Exists(uploadPath))
 18                 {
 19                     Directory.CreateDirectory(uploadPath);
 20                 }
 21                 string filepath = Path.Combine(uploadPath, file.FileName);
 22                 using (var statem = System.IO.File.Create(filepath))
 23                 {
 24                     file.CopyTo(statem);
 25                 }
 26                 return file.FileName;
 27             }
 28             catch (Exception ex) 
 29             {
 30                 return ex.Message + ex.StackTrace;
 31             }
 32         }
 33 
 34         /// <summary>
 35         /// 附件下载/游览
 36         /// </summary>
 37         /// <param name="filepath">下载文件地址+文件名</param>
 38         /// <param name="keepTypeSet">是否保留文件排版</param>
 39         /// <param name="isRead">是否在线读取为html</param>
 40         /// <returns></returns>
 41         public static object DownFile(string filepath, bool keepTypeSet, bool isRead = true)
 42         {
 43             try
 44             {
 45                 var respHtml = string.Empty;
 46                 var savePan = "./FileDown";
 47                 if (!Directory.Exists(savePan))
 48                 {
 49                     Directory.CreateDirectory(savePan);
 50                 }
 51 
 52                 var savePath = savePan + "/" + Guid.NewGuid();
 53                 if (!isRead)
 54                     return new FileStream(filepath, FileMode.Open);
 55                 var isWriteFile = false;
 56 
 57                 switch (keepTypeSet)
 58                 {
 59                     case true:
 60                         var readKeepFileInfo = keepTypeSetReadFile(filepath, savePath);
 61                         isWriteFile = readKeepFileInfo.Item1;
 62                         respHtml = readKeepFileInfo.Item2;
 63                         break;
 64                     case false:
 65                         var readFileInfo = RapidityReadFile(filepath, savePath);
 66                         isWriteFile = readFileInfo.Item1;
 67                         respHtml = readFileInfo.Item2;
 68                         break;
 69                 }
 70                 if (keepTypeSet && System.IO.File.Exists(savePath + ".pdf"))
 71                     System.IO.File.Delete(savePath + ".pdf");
 72                 if (isWriteFile)
 73                 {
 74                     var thisFile = savePath + ".html";
 75                     //文件是否存在
 76                     if (System.IO.File.Exists(thisFile))
 77                     {
 78                         Stream myStream = new FileStream(thisFile, FileMode.Open);
 79                         StreamReader myStreamReader = new StreamReader(myStream);
 80                         respHtml = myStreamReader.ReadToEnd();
 81                         myStream.Close();
 82                         //删除文件
 83                         System.IO.File.Delete(thisFile);
 84                     }
 85                     #region 创建文件删除
 86                     var saveImages = savePath + "_images";
 87                     var saveFile = savePath + "_files";
 88                     var saveCss = savePath + "_styles.css";
 89                     if (Directory.Exists(saveImages))
 90                         Directory.Delete(saveImages, true);
 91                     if (Directory.Exists(saveFile))
 92                         Directory.Delete(saveFile, true);
 93                     if (System.IO.File.Exists(saveCss))
 94                         System.IO.File.Delete(saveCss);
 95                     #endregion
 96                     //水印处理
 97                     respHtml = checkProcessingWatermark(respHtml, 
 98                         filepath.Contains(".doc") || filepath.Contains(".docx") ? true: false);
 99                 }
100                 if (!string.IsNullOrEmpty(respHtml))
101                     return respHtml;
102                 //文件下载
103                 return new FileStream(filepath, FileMode.Open); ;
104             }
105             catch (Exception ex)
106             {
107                 //return Ok("文件下载失败:" + ex.Message);
108                 return "文件下载失败:" + ex.Message;
109             }
110         }
111 
112         private static string checkProcessingWatermark(string respHtml,bool isRegex)
113         {
114             respHtml = respHtml.Replace("Evaluation&nbsp;Warning&nbsp;:&nbsp;The&nbsp;document&nbsp;was&nbsp;created&nbsp;with&nbsp;&nbsp;Spire.XLS&nbsp;for&nbsp;.NET", "");
115             respHtml = respHtml.Replace("Evaluation&nbsp;Warning&nbsp;:&nbsp;The&nbsp;document&nbsp;was&nbsp;created&nbsp;with&nbsp;Spire.PDF&nbsp;for&nbsp;.NET.", "");
116             respHtml = respHtml.Replace("Evaluation&#160;Warning&#160;:&#160;The&#160;document&#160;was&#160;created&#160;with&#160;Spire.PDF&#160;for&#160;.NET.", "");
117             respHtml = respHtml.Replace("Evaluation&nbsp;Warning&nbsp;:&nbsp;The&nbsp;document&nbsp;was&nbsp;created&nbsp;with&nbsp;Spire.Doc&nbsp;for&nbsp;.NET.", "");
118             respHtml = respHtml.Replace("Evaluation&#160;Warning&#160;:&#160;The&#160;document&#160;was&#160;created&#160;with&#160;Spire.Doc&#160;for&#160;.NET.", "");
119             respHtml = respHtml.Replace("Evaluation Warning: The document was created with Spire.Doc for .NET.", "");
120             respHtml = respHtml.Replace("Evaluation&#160;Warning&#160;:&#160;The&#160;document&#160;was&#160;created&#160;with&#160;&#160;Spire.XLS&#160;for&#160;.NET", "");
121             respHtml = respHtml.Replace("Evaluation&#160;Warning:&#160;The&#160;document&#160;was&#160;created&#160;with&#160;Spire.Doc&#160;for&#160;.NET.", "");
122             respHtml = respHtml.Replace("Spire.XLS&#160;for&#160;.NET", "");
123             respHtml = respHtml.Replace("e-iceblue&#160;Inc.&#160;2002-2021&#160;All&#160;rights&#160;reserverd", "");
124             respHtml = respHtml.Replace("Home&#160;page", "");
125             respHtml = respHtml.Replace("https://www.e-iceblue.com", "");
126             respHtml = respHtml.Replace("Contact&#160;US", "");
127             respHtml = respHtml.Replace("https://www.e-iceblue.com/Buy/Spire.XLS.html", ""); 
128             respHtml = respHtml.Replace("Buy/Spire.XLS.html", "");
129             respHtml = respHtml.Replace("Buy&#160;Now!", "");
130             respHtml = respHtml.Replace("mailto:support@e-iceblue.com", "");
131             if (isRegex)
132             {
133                 Regex reg = new Regex("<text style=.*</text>");
134                 var textGroup = reg.Matches(respHtml);
135                 var itemReg = new Regex(">.*<");
136                 var errorTxt = "Evaluation&#160;Warning:&#160;The&#160;document&#160;was&#160;created&#160;with&#160;Spire.Doc&#160;for&#160;.NET.";
137                 var thisShowText = new StringBuilder();//
138                 var splitItem = new List<string>();
139                 foreach (var item in textGroup)
140                 {
141                     splitItem.Add(item.ToString());
142                     var thisValue = itemReg.Matches(item.ToString())?[0].Value;
143                     if (string.IsNullOrEmpty(thisValue))
144                     {
145                         thisShowText = new StringBuilder();
146                         splitItem.Clear();
147                         continue;
148                     }
149                     thisValue = thisValue.TrimStart('>').TrimEnd('<');
150                     thisShowText.Append(thisValue.ToString());
151                     if (!errorTxt.Contains(thisShowText.ToString()))
152                     {
153                         thisShowText = new StringBuilder();
154                         splitItem.Clear();
155                         continue;
156                     }
157                     if (thisShowText.ToString() == errorTxt)
158                         break;
159                 }
160                 foreach (var item in splitItem)
161                 {
162                     respHtml = respHtml.Replace(item, "");
163                 }
164             }
165             return respHtml;
166         }
167 
168 
169         private static (bool, string) keepTypeSetReadFile(string filepath, string savePath)
170         {
171             if (filepath.Contains(".xlsx") || filepath.Contains(".xls"))
172                 return (keepTypeSetExcelFromSave(filepath, savePath),string.Empty);
173             if (filepath.Contains(".doc") || filepath.Contains(".docx"))
174                 return (keepTypeSetWordFromSave(filepath, savePath), string.Empty);
175             if (filepath.Contains(".pdf"))
176                 return (readPDFFromSave(filepath, savePath + ".html"), string.Empty);
177             if (filepath.Contains(".eml"))
178                 return (false, readEMLFromPath(filepath));
179             return (false, string.Empty);
180         }
181 
182         private static (bool, string) RapidityReadFile(string filepath, string savePath)
183         {
184             var respHtml = string.Empty;
185             var isWriteFile = false;
186             ////excel 转 html
187             if (filepath.Contains(".xlsx"))
188                 respHtml = readExcelXlsxFromPath(filepath);
189             else if (filepath.Contains(".xls"))
190                 isWriteFile = readExcelXlsxFromSave(filepath, savePath + ".html");
191             ////word 转 html
192             if (filepath.Contains(".doc") || filepath.Contains(".docx"))
193             {
194                 respHtml = readWordFromPath(filepath);
195                 if (string.IsNullOrEmpty(respHtml))
196                 {
197                     respHtml = readWordFromStream(filepath);
198                     if (string.IsNullOrEmpty(respHtml))
199                         isWriteFile = readWordFromSave(filepath, savePath + ".html");
200                 }
201             }
202             ////pdf 转 html
203             if (filepath.Contains(".pdf"))
204                 isWriteFile = readPDFFromSave(filepath, savePath + ".html");
205             if (filepath.Contains(".eml"))
206                 return (false, readEMLFromPath(filepath));
207             return (isWriteFile, respHtml);
208         }
209 
210         private static bool readPDFFromSave(string filepath, string savePath)
211         {
212             try
213             {
214                 //创建一个PdfDocument类实例,并加载文档 
215                 Spire.Spire.Pdf.PdfDocument pdf = new Spire.Spire.Pdf.PdfDocument(filepath);
216                 //保存文档为HTML
217                 pdf.SaveToFile(savePath, Spire.Spire.Pdf.FileFormat.HTML);
218                 return true;
219             }
220             catch (Exception ex)
221             {
222                 return false;
223             }
224         }
225 
226         private static bool keepTypeSetWordFromSave(string filepath, string savePath)
227         {
228             try
229             {
230                 var saveFile = savePath + ".pdf";
231                 Document doc = new Document(filepath);
232                 doc.SaveToFile(saveFile, Spire.Spire.Doc.FileFormat.PDF);
233                 return readPDFFromSave(saveFile, saveFile.Replace("pdf", "html"));
234             }
235             catch (Exception ex)
236             {
237                 return false;
238             }
239         }
240 
241         private static bool keepTypeSetExcelFromSave(string filepath, string savePath)
242         {
243             try
244             {
245                 //加载Excel sample
246                 Workbook workbook = new Workbook();
247                 workbook.LoadFromFile(filepath);
248                 var tempbook = new Workbook();
249                 //遍历数组
250                 for (int i = 0; i < workbook.Worksheets.Count; i++)
251                 {
252                     //获取第n个Excel工作表
253                     tempbook.Worksheets.AddCopy(workbook.Worksheets[i]);
254                 }
255                 tempbook.ConverterSetting.SheetFitToPage = true;//关键   自适应pdf
256                 tempbook.SaveToFile(savePath + ".pdf");
257 
258                 return readPDFFromSave(savePath + ".pdf", (savePath + ".pdf").Replace("pdf", "html"));
259             }
260             catch (Exception ex)
261             {
262                 return false;
263             }
264         }
265 
266         private static bool readExcelXlsxFromSave(string filepath, string savePath)
267         {
268             try
269             {
270                 //加载Excel sample
271                 Workbook workbook = new Workbook();
272                 workbook.LoadFromFile(filepath);
273                 //
274                 var tempbook = new Workbook();
275                 //遍历数组
276                 for (int i = 0; i < workbook.Worksheets.Count; i++)
277                 {
278                     //获取第n个Excel工作表
279                     tempbook.Worksheets.AddCopy(workbook.Worksheets[i]);
280                 }
281                 tempbook.SaveToFile(savePath);
282                 return true;
283             }
284             catch (Exception ex)
285             {
286                 return false;
287             }
288         }
289 
290         private static string readExcelXlsxFromPath(string filepath)
291         {
292             //保存Excel到HTML
293             return ce.office.extension.ExcelHelper.ToHtml(filepath);
294         }
295 
296         private static string readWordFromPath(string filepath)
297         {
298             try
299             {
300                 return ce.office.extension.WordHelper.ToHtml(filepath);
301             }
302             catch (Exception ex) 
303             {
304                 return string.Empty;
305             }
306         }
307                 
308         private static string readWordFromStream(string filepath)
309         {
310             try
311             {
312                 using (FileStream stream = new FileStream(filepath, FileMode.Open))
313                 {
314                     using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
315                     {
316                         return ce.office.extension.WordHelper.ConvertToHtml(wordDoc);//.ToHtml(filepath);
317                     }
318                 }
319             }
320             catch (Exception ex)
321             {
322                 return string.Empty;
323             }
324         }
325                 
326         private static bool readWordFromSave(string filepath, string savePath)
327         {
328             try
329             {
330                 Document doc = new Document(filepath);
331                 doc.SaveToFile(savePath, Spire.Spire.Doc.FileFormat.Html);
332                 return true;
333             }
334             catch (Exception ex)
335             {
336                 return false;
337             }
338         }
339 
340         private static string readEmlDataChangeHtmlStr(MailMessage email)
341         {
342             var files = email.Attachments;
343             var body = updateStrByRadom(email.BodyHtml, ref files);
344             var fileName = files.FirstOrDefault()?.FileName;
345             var mainHtml = @"
346     <div class='email-container-box'>
347         <div class='header'>
348             <h3 class='head-title'>" + email.Subject + @"</h3>
349             <p class='head-item'><span class='head-item-title'>发件人</span>:"+string.Format("<span>{0}</span><span class='grayTxt'>/{1}</span></p>", email.From.DisplayName, email.From.Address)+ @"
350             <p class='head-item'><span class='head-item-title'>时间</span>:<span class='grayTxt'>" + email.Date.ToShortDateString() + @"</span></p>
351             <p class='head-item'><span class='head-item-title'>收件人</span>:" + getToUser(email.To) + @"</p>
352             <p class='head-item'><span class='head-item-title'>抄送</span>:" + getToUserCC(email.Cc) + @"</p>
353             <p class='head-item'><span style='vertical-align: top;'  class='head-item-title'>附件</span>:<span>" + files.Count + @"</span>个(<a class='head-accessory-title' href='#footer-list' style='color:blue;' title='" + fileName + "'>" + fileName + @"</a>)</p>
354         </div>
355         <div class='body'>
356             <section>
357                 " + body + @"
358             </section>
359             <div class='footer'>
360                 <div class='footer-title'>
361                     <p class='footer-title-txt'>附件<span>" + files.Count + @"</span>个</p>
362                 </div>
363                 <div class='footer-list' id='footer-list'>
364                     " + updateStrByDownFile(files) + @"
365                 </div>
366             </div>
367         </div>
368         
369     </div>
370 
371 ";
372 
373             return mainHtml;
374         }
375 
376         private static string updateStrByDownFile(AttachmentCollection files)
377         {
378             var htmlStr = new StringBuilder("<ul>");
379             var i = 0;
380             foreach (var item in files)
381             {
382                 htmlStr.AppendFormat("<li><p id='list-titledownload{1}' class='list-title'>{0}</p><p id='filedownload{1}' class='{3}' style='display: none;'>{2}</p><p class='download'></p><p><a id='download{1}'  class='EmlDownLoad' style='color:blue;'  >下载</a></p>", item.FileName, ++i, getSrcFromStream(item), item.ContentType.MediaType.Split('/')[1]);
383             }
384             htmlStr.Append("</ul>");
385             return htmlStr.ToString();
386         }
387 
388         private static string updateStrByRadom(string htmlStr, ref AttachmentCollection files)
389         {
390             Regex reg = new Regex("<img[^<>]*?src[\\s\t\r\n]*=[\\s\t\r\n]*[\"\"']?[\\s\t\r\n]*(?<imgUrl>[^\t\r\n\"\"'<>]*)[^<>]*?/?[\\s\t\r\n]*>");
391             var textGroup = reg.Matches(htmlStr);
392             var itemReg = new Regex(":.*\"\\s");
393             foreach (var item in textGroup)
394             {
395                 if (!item.ToString().Contains("cid"))
396                     continue;
397                 var thisSrcCid = itemReg.Matches(item.ToString());
398                 if (thisSrcCid == null || !thisSrcCid.Any())
399                     continue;
400                 var thisStr = thisSrcCid.First().ToString().TrimEnd();
401                 var thisSubStr = thisStr.Substring(1, thisStr.Length - 2);
402                 var thisSrcFile = files.FirstOrDefault(s => s.ContentId == thisSubStr);
403                 if (thisSrcFile is null)
404                     continue;
405                 htmlStr = htmlStr.Replace("cid:" + thisSrcFile.ContentId, getSrcFromStream(thisSrcFile));
406                 files.Remove(thisSrcFile);
407             }
408             return htmlStr;
409         }
410 
411         private static string getSrcFromStream(Attachment file)
412         {
413             byte[] bytes = new byte[file.Data.Length];
414             file.Data.Read(bytes, 0, bytes.Length);
415             // 设置当前流的位置为流的开始 
416             file.Data.Seek(0, SeekOrigin.Begin);
417             string decodeStr = Convert.ToBase64String(bytes);
418             var dataType = "data:" + file.ContentType.MediaType.Split('/')[1] + ";base64,";//"data:image/png;base64,"
419             return dataType + decodeStr;
420         }
421 
422         private static string getToUser(MailAddressCollection to)
423         {
424             if (!to.Any())
425                 return string.Empty;
426             var resToHtml = new StringBuilder();
427             foreach (var item in to)
428             {
429                 resToHtml.AppendFormat("<span class='email-user-box'>{0}<span class='grayTxt'>({1});</span></span>", item.DisplayName , item.Address);
430             }
431             resToHtml.Append("</span>");
432             return resToHtml.ToString();
433         }
434         private static string getToUserCC(MailAddressCollection cc)
435         {
436             if (!cc.Any())
437                 return string.Empty;
438             var resToHtml = new StringBuilder();
439             foreach (var item in cc)
440             {
441                 resToHtml.AppendFormat("<span class='email-user-box'>{0}</span><span class='grayTxt'>({1});</span>", item.DisplayName, item.Address);
442             }
443             resToHtml.Append("</span>");
444             return resToHtml.ToString();
445         }
446         public static string readEMLFromPath(string filepath)
447         {
448             MailMessage email = MailMessage.Load(filepath);
449             var resHtml = readEmlDataChangeHtmlStr(email);
450             return resHtml;
451         }
452     }

 

相关文章
我们已经准备好了,你呢?
2024我们与您携手共赢,为您的企业形象保驾护航