123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406 |
- using DocumentFormat.OpenXml.Packaging;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using PdfSharpCore.Pdf;
- using PdfSharpCore.Pdf.IO;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Threading.Tasks;
- using System.Xml;
- using System.Xml.Linq;
- using TEAMModelOS.SDK.Context.Configuration;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.Context.Constant.Common;
- using TEAMModelOS.SDK.Context.Exception;
- using TEAMModelOS.SDK.Extension.DataResult.JsonRpcRequest;
- using TEAMModelOS.SDK.Extension.DataResult.JsonRpcResponse;
- using TEAMModelOS.SDK.Helper.Common.StringHelper;
- using TEAMModelOS.SDK.Helper.Security.ShaHash;
- using TEAMModelOS.SDK.Module.AzureBlob.Container;
- namespace HiTeachCE.Controllers
- {
- [Route("api/[controller]")]
- [ApiController]
- public class FileController
- {
- static XmlNamespaceManager xmlnsManager;
- static FileController()
- {
- xmlnsManager = new XmlNamespaceManager(new NameTable());
- xmlnsManager.AddNamespace("p", "http://schemas.openxmlformats.org/presentationml/2006/main");
- xmlnsManager.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");
- xmlnsManager.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
- xmlnsManager.AddNamespace("fo", "http://www.w3.org/1999/XSL/Format");
- xmlnsManager.AddNamespace("app", "http://schemas.openxmlformats.org/officeDocument/2006/extended-properties");
- xmlnsManager.AddNamespace("cp", "http://schemas.openxmlformats.org/package/2006/metadata/core-properties");
- xmlnsManager.AddNamespace("dc", "http://purl.org/dc/elements/1.1/");
- xmlnsManager.AddNamespace("dcterms", "http://purl.org/dc/terms/");
- xmlnsManager.AddNamespace("dcmitype", "http://purl.org/dc/dcmitype/");
- xmlnsManager.AddNamespace("rel", "http://schemas.openxmlformats.org/package/2006/relationships");
- xmlnsManager.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
- xmlnsManager.AddNamespace("cus", "http://schemas.openxmlformats.org/officeDocument/2006/custom-properties");
- xmlnsManager.AddNamespace("vt", "http://schemas.openxmlformats.org/officeDocument/2006/docPropsVTypes");
- xmlnsManager.AddNamespace("pic", "http://schemas.openxmlformats.org/drawingml/2006/picture");
- xmlnsManager.AddNamespace("dsp", "http://schemas.microsoft.com/office/drawing/2008/diagram");
- xmlnsManager.AddNamespace("dgm", "http://schemas.openxmlformats.org/drawingml/2006/diagram");
- xmlnsManager.AddNamespace("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
- xmlnsManager.AddNamespace("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
- xmlnsManager.AddNamespace("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
- xmlnsManager.AddNamespace("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
- xmlnsManager.AddNamespace("pkg", "http://schemas.microsoft.com/office/2006/xmlPackage");
- xmlnsManager.AddNamespace("p15", "http://schemas.microsoft.com/office/powerpoint/2012/main");
- xmlnsManager.AddNamespace("a16", "http://schemas.microsoft.com/office/drawing/2014/main");
- xmlnsManager.AddNamespace("xsi", "http://www.w3.org/2001/XMLSchema-instance");
- xmlnsManager.AddNamespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");
- xmlnsManager.AddNamespace("c14", "http://schemas.microsoft.com/office/drawing/2007/8/2/chart");
- xmlnsManager.AddNamespace("c16", "http://schemas.microsoft.com/office/drawing/2014/chart");
- xmlnsManager.AddNamespace("cs", "http://schemas.microsoft.com/office/drawing/2012/chartStyle");
- xmlnsManager.AddNamespace("thm15", "http://schemas.microsoft.com/office/thememl/2012/main");
- xmlnsManager.AddNamespace("fn", "http://www.w3.org/2005/xpath-functions");
- }
-
- /// <summary>
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("upload")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<BaseJosnRPCResponse> upload([FromForm] IFormFile file)
- {
- //if (!IsImage(file.OpenReadStream())) {
- // throw new BizException("请上传图片类型的文件!", 2);
- //}
-
- JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
- string filname = ShaHashHelper.GetSHA1(file.OpenReadStream());
- string extension = System.IO.Path.GetExtension(file.FileName).ToLower();
- // Dictionary<string, object> model = await fileService.UploadDocument(file);
- string path = BaseConfigModel.ContentRootPath + "/Avatar/" + filname + extension;
- if (System.IO.File.Exists(path) == false)
- {
- using (var stream = new FileStream(path, FileMode.Create))
- {
- await file.CopyToAsync(stream);
- }
- }
- var url = "https://cdhabook.teammodel.cn/avatar/" + filname + extension;
- return responseBuilder.Data(url).build();
-
- }
- [HttpPost("uploadBase64")]
- public BaseJosnRPCResponse UploadBase64(JosnRPCRequest<string> files)
- {
- string filname = ShaHashHelper.GetSHA1(files.@params);
- JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
- string[] strs = files.@params.Split(',');
- string fileExt = StringHelper.SubMidString(strs[0], ":", ";");
- if (ContentTypeDict.extdict.TryGetValue(fileExt, out string ext))
- {
- fileExt = ext;
- }
- else
- {
- //解决多种扩展名不能获取的
- string[] sp = StringHelper.SubMidString(strs[0], "/", ";").Split("-");
- fileExt = sp[sp.Length - 1];
- sp = fileExt.Split("+");
- fileExt = "." + sp[sp.Length - 1];
- }
- string path = BaseConfigModel.ContentRootPath + "/Avatar/" + filname + fileExt;
- if (System.IO.File.Exists(path) == false)
- {
- FileStream fs = new FileStream(path, FileMode.Create);
- BinaryWriter bw = new BinaryWriter(fs);
- bw.Write(Convert.FromBase64String(strs[1]));
- bw.Close();
- fs.Close();
- }
- var url = "https://cdhabook.teammodel.cn/avatar/" + filname + fileExt;
- return responseBuilder.Data(url).build();
- }
- /// <summary>
- /// docUrl
- /// folder
- /// shaCode
- /// </summary>
- /// <param name="request"></param>
- /// <returns></returns>
- [HttpPost("uploadDocument")]
- [RequestSizeLimit(102_400_000_00)] //最大10000m左右
- public async Task<BaseJosnRPCResponse> UploadDocument([FromForm] IFormFile file)
- {
-
- Dictionary<string, object> resdict = new Dictionary<string, object>();
- string contentRootPath = BaseConfigModel.ContentRootPath;
- JsonRPCResponseBuilder responseBuilder = new JsonRPCResponseBuilder();
- XmlDocument xmlDocument = new XmlDocument();
- string path = contentRootPath + "/OfficeFile/";
- string filname = ShaHashHelper.GetSHA1(file.OpenReadStream());
- string extension = System.IO.Path.GetExtension(file.FileName).ToLower();
- if (extension.Equals(".ppt") || extension.Equals(".doc") || extension.Equals(".pptx") || extension.Equals(".docx"))
- {
- if (System.IO.File.Exists(path + filname + ".pdf") == false)
- {
- //Console.WriteLine(filname + " Not Exists!");
- //if (extension.Equals(".ppt") || extension.Equals(".doc") || extension.Equals(".pptx") || extension.Equals(".docx"))
- //{
- //}
- //else
- //{
- // throw new BizException("file type does not support!", 500);
- //}
- if (extension.Equals(".pptx"))
- {
- using (PresentationDocument presentationDocument = PresentationDocument.Open(file.OpenReadStream(), false))
- {
- if (presentationDocument == null)
- {
- throw new ArgumentNullException("presentationDocument");
- }
- XDocument xdoc = presentationDocument.ToFlatOpcDocument();
- xmlDocument.LoadXml(xdoc.ToString());
- XmlNodeList xmlNodeList = xmlDocument.SelectNodes(@"//mc:Fallback", xmlnsManager);
- foreach (XmlNode nodeChild in xmlNodeList)
- {
- nodeChild.ParentNode.RemoveChild(nodeChild);
- }
- XmlNodeList xmlNodeListMp4 = xmlDocument.SelectNodes(@"//pkg:part[@pkg:contentType='video/mp4']", xmlnsManager);
- XmlDocument document = new XmlDocument();
- foreach (XmlNode nodeChild in xmlNodeListMp4)
- {
- throw new BizException("Please delete the video!/请删除视频再重新上传!", 1001);
- }
- XmlNodeList xmlNodeListMp3 = xmlDocument.SelectNodes(@"//pkg:part[@pkg:contentType='audio/mpeg']", xmlnsManager);
- foreach (XmlNode nodeChild in xmlNodeListMp3)
- {
- throw new BizException("Please delete the audio!/请删除音频再重新上传!", 1001);
- }
- var node = xmlDocument.Clone().OuterXml;
- XDocument xdocs = XDocument.Parse(node);
- presentationDocument.Dispose();
- using (PresentationDocument presentationDocumen1t = PresentationDocument.FromFlatOpcDocument(xdocs))
- {
- presentationDocumen1t.SaveAs(path + filname + ".pptx");
- presentationDocumen1t.Dispose();
- }
- }
- OnWork(path + filname + ".pptx");
- }
- else
- {
- Stream sourceStream = file.OpenReadStream();
- OnWork(sourceStream, path + filname + extension);
- }
- }
- //else { Console.WriteLine(filname + " Exists!"); }
- }
- else if (extension.Equals(".pdf"))
- {
- if (System.IO.File.Exists(path + filname + ".pdf") == false)
- {
- //// pdf
- string pathpdf = path + filname + ".pdf";
- using (var stream = new FileStream(pathpdf, FileMode.Create))
- {
- await file.CopyToAsync(stream);
- }
- /////
- }
- }
- else {
- throw new BizException("不支持的文件类型!",2);
- }
- PdfDocument inputDocument = PdfSharpCore.Pdf.IO.PdfReader.Open(path + filname + ".pdf", PdfDocumentOpenMode.Import);
- int count = inputDocument.PageCount;
- int limit = BaseConfigModel.Configuration.GetSection("PDFLimit").Get<int>();
- if (count > limit)
- {
- throw new BizException("PDF file cannot exceed " + limit + " pages!", 500);
- }
- //await ProcessPDF(file, resdict);
- resdict.Add("page", count);
- resdict.Add("type", "pdf");
- resdict.Add("model", new AzureBlobModel()
- {
- Folder = "OfficeFile",
- Sha1Code = filname,
- BlobUrl = "https://cdhabook.teammodel.cn/pdf/" + filname + ".pdf",
- ContentType = "application/pdf",
- ContentDisposition = "form-data; name=\"file\"; filename=\"" + filname + ".pdf\"",
- Length = inputDocument.FileSize,
- Name = "file",
- FileName = filname + ".pdf",
- RealName = "OfficeFile/" + filname + ".pdf",
- UploadTime = DateTime.Now.ToUniversalTime().Ticks - 621355968000000000,
- Extension = "pdf"
- });
- return responseBuilder.Data(resdict).build();
- }
- private bool SaveToFile(Stream stream, string path)
- {
- try
- {
- byte[] sourceBuffer = new Byte[stream.Length];
- stream.Read(sourceBuffer, 0, sourceBuffer.Length);
- stream.Seek(0, SeekOrigin.Begin);
- using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.Write))
- {
- fs.Write(sourceBuffer, 0, sourceBuffer.Length);
- fs.Close();
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine("读取PPT源文件到本地失败:" + ex.Message);
- return false;
- }
- return true;
- }
- public bool OnWork(Stream stream, string path)
- {
- string sourcePath = string.Empty;
- string destPath = string.Empty;
- try
- {
- //if (FileInfo == null)
- // return false;
- // Stream sourceStream = FileInfo.OpenReadStream();
- // string filename = FileInfo.FileName;
- // string extension = System.IO.Path.GetExtension(FileInfo.FileName);
- // sourcePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename + extension);
- //destPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), string.Format("{0}.pdf", filename));
- if (!SaveToFile(stream, path))
- {
- return false;
- }
- var psi = new ProcessStartInfo("libreoffice", string.Format(" --headless --invisible --convert-to pdf {0} --outdir /www/apps/HiTeachCE/OfficeFile/", path)) { RedirectStandardOutput = true };
- Console.WriteLine(path);
- // psi = new ProcessStartInfo("pptx2pdf ", "/www/apps/pptx2pdf/OfficeFile/5e4df6b8-6fbf-4de0-9c94-8de4b5604e45.pptx") { RedirectStandardOutput = true };
- // 启动
- var proc = Process.Start(psi);
- if (proc == null)
- {
- Console.WriteLine("不能执行.");
- return false;
- }
- else
- {
- Console.WriteLine("-------------开始执行--------------");
- //开始读取
- using (var sr = proc.StandardOutput)
- {
- while (!sr.EndOfStream)
- {
- Console.WriteLine(sr.ReadLine());
- }
- if (!proc.HasExited)
- {
- proc.Kill();
- }
- }
- Console.WriteLine("---------------执行完成------------------");
- Console.WriteLine($"退出代码 : {proc.ExitCode}");
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return false;
- }
- finally
- {
- //if (System.IO. File.Exists(destPath))
- //{
- // var destFileInfo = UploadFile(destPath, string.Format("{0}.pdf", Path.GetFileNameWithoutExtension( FileInfo.FileName)));
- //}
- //if (System.IO.File.Exists(destPath))
- //{
- // System.IO.File.Delete(destPath);
- //}
- }
- return true;
- }
- public bool OnWork(string path)
- {
- // string sourcePath = string.Empty;
- // string destPath = string.Empty;
- try
- {
- //if (FileInfo == null)
- // return false;
- // Stream sourceStream = FileInfo.OpenReadStream();
- // string filename = FileInfo.FileName;
- // string extension = System.IO.Path.GetExtension(FileInfo.FileName);
- // sourcePath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), filename + extension);
- //destPath = System.IO.Path.Combine(Directory.GetCurrentDirectory(), string.Format("{0}.pdf", filename));
- //if (!SaveToFile(sourceStream, sourcePath))
- // return false;
- var psi = new ProcessStartInfo("libreoffice", string.Format(" --headless --invisible --convert-to pdf {0} --outdir /www/apps/HiTeachCE/OfficeFile/", path)) { RedirectStandardOutput = true };
- Console.WriteLine(path);
- // psi = new ProcessStartInfo("pptx2pdf ", "/www/apps/pptx2pdf/OfficeFile/5e4df6b8-6fbf-4de0-9c94-8de4b5604e45.pptx") { RedirectStandardOutput = true };
- // 启动
- var proc = Process.Start(psi);
- if (proc == null)
- {
- Console.WriteLine("不能执行.");
- return false;
- }
- else
- {
- Console.WriteLine("-------------开始执行--------------");
- //开始读取
- using (var sr = proc.StandardOutput)
- {
- while (!sr.EndOfStream)
- {
- Console.WriteLine(sr.ReadLine());
- }
- if (!proc.HasExited)
- {
- proc.Kill();
- }
- }
- Console.WriteLine("---------------执行完成------------------");
- Console.WriteLine($"退出代码 : {proc.ExitCode}");
- }
- }
- catch (Exception ex)
- {
- Console.WriteLine(ex.Message);
- return false;
- }
- finally
- {
- //if (System.IO. File.Exists(destPath))
- //{
- // var destFileInfo = UploadFile(destPath, string.Format("{0}.pdf", Path.GetFileNameWithoutExtension( FileInfo.FileName)));
- //}
- //if (System.IO.File.Exists(destPath))
- //{
- // System.IO.File.Delete(destPath);
- //}
- }
- return true;
- }
- }
- }
|