文件的上传/下载+在线游览(转化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 Warning : The document was created with Spire.XLS for .NET", "");
115 respHtml = respHtml.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "");
116 respHtml = respHtml.Replace("Evaluation Warning : The document was created with Spire.PDF for .NET.", "");
117 respHtml = respHtml.Replace("Evaluation Warning : The document was created with Spire.Doc for .NET.", "");
118 respHtml = respHtml.Replace("Evaluation Warning : The document was created with Spire.Doc for .NET.", "");
119 respHtml = respHtml.Replace("Evaluation Warning: The document was created with Spire.Doc for .NET.", "");
120 respHtml = respHtml.Replace("Evaluation Warning : The document was created with Spire.XLS for .NET", "");
121 respHtml = respHtml.Replace("Evaluation Warning: The document was created with Spire.Doc for .NET.", "");
122 respHtml = respHtml.Replace("Spire.XLS for .NET", "");
123 respHtml = respHtml.Replace("e-iceblue Inc. 2002-2021 All rights reserverd", "");
124 respHtml = respHtml.Replace("Home page", "");
125 respHtml = respHtml.Replace("https://www.e-iceblue.com", "");
126 respHtml = respHtml.Replace("Contact 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 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 Warning: The document was created with Spire.Doc for .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 }
文件的上传/下载+在线游览(转化html)--不需要在线插件//自己写的小方法的更多相关文章
- 在Window的IIS中创建FTP的Site并用C#进行文件的上传下载
文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服务器计算机上. 然后,远程计算机可以使用 FTP ...
- 创建FTP的Site并用C#进行文件的上传下载
创建FTP的Site并用C#进行文件的上传下载 文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服 ...
- linux链接及文件互相上传下载
若排版紊乱可查看我的个人博客原文地址 基本操作 本篇博客主要介绍如何去链接远程的linux主机及如何实现本地与远程主机之间文件的上传下载操作,下面的linux系统是CentOS6.6 链接远程linu ...
- Spring实现文件的上传下载
背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...
- SocketIo+SpringMvc实现文件的上传下载
SocketIo+SpringMvc实现文件的上传下载 socketIo不仅可以用来做聊天工具,也可以实现局域网(当然你如果有外网也可用外网)内实现文件的上传和下载,下面是代码的效果演示: GIT地址 ...
- JAVAWEB之文件的上传下载
文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...
- SSM框架之中如何进行文件的上传下载
SSM框架的整合请看我之前的博客:http://www.cnblogs.com/1314wamm/p/6834266.html 现在我们先看如何编写文件的上传下载:你先看你的pom.xml中是否有文件 ...
- python使用ftplib模块实现FTP文件的上传下载
python已经默认安装了ftplib模块,用其中的FTP类可以实现FTP文件的上传下载 FTP文件上传下载 # coding:utf8 from ftplib import FTP def uplo ...
- php文件夹上传下载控件分享
用过浏览器的开发人员都对大文件上传与下载比较困扰,之前遇到了一个php文件夹上传下载的问题,无奈之下自己开发了一套文件上传控件,在这里分享一下.希望能对你有所帮助. 以下是实例的部分脚本文件 这里我先 ...
- 使用Fileupload完成文件的上传下载
目录 使用Fileupload完成文件的上传下载 为什么需要进行文件上传下载? 引入jar包 文件上传 注意事项 编写一个简单的文件上传jsp页面 编写Servlet Student类用于封装数据,后 ...
随机推荐
- day021|python之面向对象进阶1
面向对象进阶 目录 面向对象进阶 1 继承 1.1 继承入门 1.1.1 继承基础 1.1.2 类的基本使用 1.2 多继承 1.2.1 多继承的基本使用 1.2.2 多继承以后的重复性 1.3 类的 ...
- Ubuntu使用Nginx 部署你的静态网页
首先使用Putty 登录填写名称 unbutu 然后获取管理员权限 sudo -i 首先更新APT库sudo apt-get updatesudo apt-get upgrade 安装 git,su ...
- NET 5 Session、Cookie和Cache的使用
1.Cookie public IConfiguration Configuration { get; } // This method gets called by the runtime. Use ...
- 7.自定义ViewGroup-下滑抽屉
1.效果 2.思路 分析效果: 1.布局分为两部分,后面部分,前面部分,默认状态后面被挡住: 2.后面不可以滑动,前面可以滑动: 3.如果前面的布局本身是可以滑动的,那么当前面布局滑动到第一个时,后面 ...
- 要多用Java帮助文档
从第一次接触Java到现在,大概两年了吧,间断断续续的学习.毕竟还在上课,其他课程也挺耗时间,但更多的还是自己不自律,很多时间都在玩. 平时用的有eclipse和IDEA,使用快捷方式有时看看源码,也 ...
- 微软自动化测试工具palywright
前言 我们介绍许多e2e的自动化测试工具 一类是基于 Selenium 的测试框架: robot framework gauge SeleniumBase seldom(我自己维护的) 另一类是基于J ...
- spring mvc 集成quartz
首先quartz配置文件 # Default Properties file for use by StdSchedulerFactory # to create a Quartz Scheduler ...
- CentOS 8 安装mysql8.0.21
1.使用dnf安装mysql(遇到暂停按y)dnf install @mysql 2.安装完成使用下面命令启动MySQL服务systemctl enable --now mysqld 3.查看服务是否 ...
- ESXi 中重新启动管理代理
使用直接控制台用户界面 (DCUI)重启管理代理: 连接到您的 ESXi 主机的控制台. 按 F2 自定义系统. 以 root 身份登录. 使用上下箭头导航至故障排除选项>重新启动管理代理. 按 ...
- java数组之排序
/** * String排序算法依据<b>词典编排顺序排序</b><br> * 所以大写字母开头的词都放在前面输出,之后才是小写之母开头的词 *@date:2018 ...