using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Learun.Application.Base.SystemModule;
using Learun.Application.OA.File.FilePreview;
using Learun.Util;
using O2S.Components.PDFRender4NET;
namespace Learun.Application.Web.Areas.LR_SystemModule.Controllers
{
///
/// 版 本 PIT-ADMS V7.0.3 敏捷开发框架
/// Copyright (c) 2013-2018 Hexagon PPM
/// 创建人:研发部
/// 日 期:2017.03.08
/// 描 述:附件管理
///
public class AnnexesController : MvcControllerBase
{
private AnnexesFileIBLL annexesFileIBLL = new AnnexesFileBLL();
#region 视图功能
///
/// 上传列表页面
///
///
[HttpGet]
public ActionResult UploadForm()
{
return View();
}
///
/// 下载列表页面
///
///
[HttpGet]
public ActionResult DownForm()
{
return View();
}
///
/// 图片预览页面
///
///
[HttpGet]
public ActionResult PictureView(string fileId)
{
ViewBag.fileId = fileId;
return View();
}
///
/// 图片预览页面
///
///
[HttpGet]
public ActionResult PicturePreView(string fileId)
{
ViewBag.fileId = fileId;
return View();
}
#endregion
#region 提交数据
///
/// 上传附件分片数据
///
/// 文件主键
/// 分片序号
/// 文件数据
///
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult UploadAnnexesFileChunk(string fileGuid, int chunk, int chunks, HttpPostedFileBase Filedata)
{
//没有文件上传,直接返回
if (Filedata == null || string.IsNullOrEmpty(Filedata.FileName) || Filedata.ContentLength == 0)
{
if (Request.Files.Count > 0)
{
Filedata = Request.Files[0];
}
else
{
return HttpNotFound();
}
}
annexesFileIBLL.SaveChunkAnnexes(fileGuid, chunk, Filedata.InputStream);
return Success("保存成功");
}
///
/// 移除附件分片数据
///
/// 文件主键
/// 总分片数
///
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult RemoveAnnexesFileChunk(string fileGuid, int chunks)
{
annexesFileIBLL.RemoveChunkAnnexes(fileGuid, chunks);
return Success("移除成功");
}
/////
///// 合并上传附件的分片数据
/////
///// 附件夹主键
///// 文件主键
///// 文件名
///// 文件总分片数
/////
//[HttpPost]
//[ValidateAntiForgeryToken]
//public ActionResult MergeAnnexesFile(string folderId, string fileGuid, string fileName, int chunks)
//{
// UserInfo userInfo = LoginUserInfo.Get();
// bool res = annexesFileIBLL.SaveAnnexes(folderId, fileGuid, fileName, chunks, userInfo);
// if (res)
// {
// return Success("保存文件成功");
// }
// else
// {
// return Fail("保存文件失败");
// }
//}
///
/// 合并上传附件的分片数据(固定文件夹)
///
/// 附件夹主键
/// 文件主键
/// 文件名
/// 文件总分片数
///
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult MergeAnnexesFile(string folderId, string fileGuid, string fileName, int chunks, string filePath)
{
UserInfo userInfo = LoginUserInfo.Get();
string path = "";
if (string.IsNullOrEmpty(filePath))
{
path = Config.GetValue(filePath);
//如果是相对路径先转换成绝对路径
if (path.Contains("~"))
{
path = Server.MapPath(path);
}
}
//string path = HttpRuntime.AppDomainAppPath.ToString();
bool res = annexesFileIBLL.SaveAnnexes(folderId, fileGuid, fileName, chunks, userInfo, path);
if (res)
{
return Success("保存文件成功");
}
else
{
return Fail("保存文件失败");
}
}
///
/// 删除文件
///
/// 文件主键
///
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult DeleteAnnexesFile(string fileId)
{
AnnexesFileEntity fileInfoEntity = annexesFileIBLL.GetEntity(fileId);
annexesFileIBLL.DeleteEntity(fileId);
//删除文件
if (System.IO.File.Exists(fileInfoEntity.F_FilePath))
{
//System.IO.File.Delete(fileInfoEntity.F_FilePath);
//避免公司端删了一些块文件等,对项目上产生影响。因为annexesfile表中,指向的物理路径是同一个。因为新建项目时,只是变了folderid,但是F-filepath是不变的。
}
return Success("删除附件成功");
}
#endregion
#region 获取数据
///
/// 下载文件
///
/// 文件id
///
[HttpPost]
[ValidateAntiForgeryToken]
public void DownAnnexesFile(string fileId)
{
var data = annexesFileIBLL.GetEntity(fileId);
string filename = Server.UrlDecode(data.F_FileName);//返回客户端文件名称
string filepath = data.F_FilePath;
if (FileDownHelper.FileExists(filepath))
{
FileDownHelper.DownLoad("", filepath, filename);
}
}
///
/// 获取附件列表
///
/// 附件夹主键
///
[HttpGet]
public ActionResult GetAnnexesFileList(string folderId)
{
List data = annexesFileIBLL.GetList(folderId);
if(data!=null && data.Count > 0)
{
data.ForEach(d => { d.F_FilePath = ""; d.F_ThumbnailImgPath = ""; });
}
return Success(data);
}
///
/// 获取附件夹信息
///
/// 附件夹主键
///
[HttpGet]
public ActionResult GetFileNames(string folderId)
{
var data = annexesFileIBLL.GetFileNames(folderId);
return Success(data);
}
///
/// 获取页面显示列表数据
///
/// 查询参数
///
[HttpGet]
[AjaxOnly]
public ActionResult GetPageList(string pagination, string queryJson)
{
Pagination paginationobj = pagination.ToObject();
paginationobj.sidx = "F_CreateDate";
List data = annexesFileIBLL.GetPageList(paginationobj, queryJson);
if (data != null && data.Count > 0)
{
data.ForEach(d => { d.F_FilePath = ""; d.F_ThumbnailImgPath = ""; });
}
var jsonData = new
{
rows = data,
total = paginationobj.total,
page = paginationobj.page,
records = paginationobj.records
};
return Success(jsonData);
}
#endregion
#region 预览附件
///
/// 文件预览
///
/// 文件ID
///
public void PreviewFile(string fileId)
{
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
var data = annexesFileIBLL.GetEntity(fileId);
if (data == null)
{
return;
}
string filename = data.F_FileName;//客户端保存的文件名
//路径
string filepath = data.F_FilePath;
if (!System.IO.File.Exists(filepath))
{
return;
}
if (data.F_FileType == "xlsx" || data.F_FileType == "xls")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetExcelData(data.F_FilePath);
}
}
if (data.F_FileType == "docx" || data.F_FileType == "doc")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetWordData(data.F_FilePath);
}
}
if (data.F_FileType == "ppt" || data.F_FileType == "pptx" || data.F_FileType == "pdf")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetPptData(data.F_FilePath);
}
}
if (data.F_FileType == "tif")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetTifData(data.F_FilePath);
}
}
Response.ClearContent();
switch (data.F_FileType)
{
case "jpg":
Response.ContentType = "image/jpeg";
break;
case "gif":
Response.ContentType = "image/gif";
break;
case "png":
Response.ContentType = "image/png";
break;
case "bmp":
Response.ContentType = "application/x-bmp";
break;
case "jpeg":
Response.ContentType = "image/jpeg";
break;
case "doc":
case "docx":
case "ppt":
case "pptx":
case "xls":
case "xlsx":
case "pdf":
Response.ContentType = "application/pdf";
break;
case "txt":
Response.ContentType = "text/plain";
Response.Charset = "UTF-8";
break;
case "csv":
Response.ContentType = "";
break;
case "mp4":
Response.ContentType = "video/mp4";
break;
default:
Response.ContentType = "application/pdf";
break;
}
if (data.F_FileType != "txt")
{
Response.Charset = "GB2312";
}
Response.WriteFile(filepath);
//Response.BinaryWrite(ms.ToArray());
}
///
/// 缩略图是否存在
///
/// 文件ID
[HttpGet]
[AjaxOnly]
public bool IsExist(string fileId)
{
var data = annexesFileIBLL.GetEntity(fileId);
if (data != null)
{
//缩略图是否存在
if (!string.IsNullOrWhiteSpace(data.F_ThumbnailImgPath))
{
return true;
}
}
return false;
}
///
/// 缩略图预览
///
/// 文件ID
///
public void PreviewThumbnailImg(string fileId)
{
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
var data = annexesFileIBLL.GetEntity(fileId);
if (data == null)
{
return;
}
//缩略图路径
string thumbnailImgPath = data.F_ThumbnailImgPath;
if (!System.IO.File.Exists(thumbnailImgPath))
{
return;
}
Response.ClearContent();
switch (data.F_FileType)
{
case "jpg":
Response.ContentType = "image/jpeg";
break;
case "gif":
Response.ContentType = "image/gif";
break;
case "png":
Response.ContentType = "image/png";
break;
case "bmp":
Response.ContentType = "application/x-bmp";
break;
case "jpeg":
Response.ContentType = "image/jpeg";
break;
default:
Response.ContentType = "image/jpeg";
break;
}
if (data.F_FileType != "txt")
{
Response.Charset = "GB2312";
}
Response.WriteFile(thumbnailImgPath);
}
///
/// 缩略图预览
///
/// 文件ID
///
public void PreviewImg(string F_ThumbnailImgPath)
{
if (string.IsNullOrEmpty(F_ThumbnailImgPath))
{
return;
}
//缩略图路径
string thumbnailImgPath = F_ThumbnailImgPath;
if (!System.IO.File.Exists(thumbnailImgPath))
{
return;
}
Response.ClearContent();
var lenthofimg = F_ThumbnailImgPath.Split('.');
switch (lenthofimg[lenthofimg.Length - 1])
{
case "jpg":
Response.ContentType = "image/jpeg";
break;
case "gif":
Response.ContentType = "image/gif";
break;
case "png":
Response.ContentType = "image/png";
break;
case "bmp":
Response.ContentType = "application/x-bmp";
break;
case "jpeg":
Response.ContentType = "image/jpeg";
break;
default:
Response.ContentType = "image/jpeg";
break;
}
//if (data.F_FileType != "txt")
//{
// Response.Charset = "GB2312";
//}
Response.WriteFile(thumbnailImgPath);
}
///
/// App端文件转成pdf
///
/// 文件ID
[HttpGet]
[AjaxOnly]
public ActionResult GetPdf(string fileId)
{
string AnnexesFileToIIS = Config.GetValue("AnnexesFileToIIS", "0");
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
var data = annexesFileIBLL.GetEntity(fileId);
string filename = data.F_FileName;//客户端保存的文件名
//路径
string filepath = data.F_FilePath;
if (!System.IO.File.Exists(filepath))
{
return Fail("文件已被删除"); ;
}
bool isPdf = false;
if (data.F_FileType == "xlsx" || data.F_FileType == "xls")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetExcelData(data.F_FilePath);
}
isPdf = true;
}
if (data.F_FileType == "docx" || data.F_FileType == "doc")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetWordData(data.F_FilePath);
}
isPdf = true;
}
if (data.F_FileType == "ppt" || data.F_FileType == "pptx")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetPptData(data.F_FilePath);
}
isPdf = true;
}
if (data.F_FileType == "tif")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetTifData(data.F_FilePath);
}
isPdf = true;
}
if (data.F_FileType == "txt")
{
filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名
if (!DirFileHelper.IsExistFile(filepath))
{
filePreviewIBLL.GetTxtData(data.F_FilePath);
}
isPdf = true;
}
if (data.F_FileType == "pdf")//pdf 直接返回路径地址
{
isPdf = true;
return Success("转换成功", new { filepath = filepath, AnnexesFileToIIS });
}
if (isPdf)
{
return Success("转换成功", new { filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf", AnnexesFileToIIS });
}
return Fail("不能转化为PDF文件");
}
///
/// 获取video路径
///
/// 文件ID
[HttpGet]
[AjaxOnly]
public ActionResult GetVideo(string folderId)
{
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
var data = annexesFileIBLL.GetList(folderId);
if (data != null && data.Count > 0)
{
//路径
string filepath = data[0].F_FilePath;
if (!System.IO.File.Exists(filepath))
{
return Fail("文件已被删除");
}
return Success(filepath);
}
else
{
return Fail("请先上传视频");
}
}
#endregion
#region 将Pptx文档转换为图片
///
/// 将Pptx文档转换为图片
///
/// 附件夹主键
///
//public List ConvertPptxToImg(string folderId)
//{
// List listSplitUrl = new List();
// List data = annexesFileIBLL.GetEntitys(folderId);
// if (data != null && data.Count > 0)
// {
// string filename = data[0].F_FileName;//返回客户端文件名称
// string pptPath = data[0].F_FilePath; //路径
// string directoryName = filename.Split('.')[0];//获取选择文件名称
// string vdir = "";
// string imgPath = Config.GetValue("ConvertPptxToImg");
// UserInfo userInfo = LoginUserInfo.Get();
// // vdir = UserId/年/月/日/文件名称
// vdir = "{2}/{3}/{4}/{5}";
// vdir = string.Format(vdir, userInfo.userId, DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, directoryName);
// imgPath = Path.Combine(imgPath, vdir);
// if (!Directory.Exists(imgPath))
// {
// Directory.CreateDirectory(imgPath);
// var app = new Microsoft.Office.Interop.PowerPoint.Application();
// var ppt = app.Presentations.Open(pptPath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse);
// var index = 0;
// var fileName = Path.GetFileNameWithoutExtension(pptPath);
// foreach (Microsoft.Office.Interop.PowerPoint.Slide slid in ppt.Slides)
// {
// ++index;
// //设置图片大小
// string ChildDir = string.Format("{0}{1}.png", directoryName, index.ToString());
// string imageName = Path.Combine(imgPath, ChildDir);
// imageName = imageName.Replace('/', '\\');
// slid.Export(imageName, "png", 1024, 768);
// //int len = imageName.LastIndexOf("Content");
// //var imageurl = "\\" + imageName.Substring(len, imageName.Length - len);
// //imageurl = imageurl.Replace('\\', '/');
// string imageurl = imageName.Replace('\\', '/');
// listSplitUrl.Add(imageurl.Replace("C:", ""));
// //根据屏幕尺寸。设置图片大小
// //slid.Export(imgPath+string.Format("page{0}.jpg",index.ToString()), "jpg", Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height);
// }
// //释放资源
// ppt.Close();
// app.Quit();
// GC.Collect();
// }
// else
// {
// Directory.Delete(imgPath, true);
// }
// //转换成html
// //string path = Config.GetValue("PowerPointToHtml") + "/" + directoryName + ".html";
// //if (!DirFileHelper.IsExistFile(path))
// //{
// // filePreviewIBLL.ConvertPptxToHtml(data[0].F_FilePath, path);
// //}
// }
// return listSplitUrl;
//}
#endregion
#region 将Pptx文档转换为Html
///
/// 将Pptx文档转换为Html
///
/// 附件夹主键
///
public string ConvertPptxToHtml(string folderId)
{
string htmlPath = string.Empty;
List data = annexesFileIBLL.GetEntitys(folderId);
if (data != null && data.Count > 0)
{
string directoryName = data[0].F_FileName.Split('.')[0].Replace(" ", "");//获取选择文件名称
string vdir = "";
string pptxToHtmlPath = Config.GetValue("ConvertPptxToHtml");
UserInfo userInfo = LoginUserInfo.Get();
vdir = "{1}/{2}/{3}/{4}";
vdir = string.Format(vdir, userInfo.userId, folderId, DateTime.Now.ToString("yyyyMMdd"), directoryName);
pptxToHtmlPath = Path.Combine(pptxToHtmlPath, vdir);
string tempDirectory = pptxToHtmlPath;
vdir = string.Format("{0}.html", directoryName);
pptxToHtmlPath = Path.Combine(pptxToHtmlPath, vdir);
pptxToHtmlPath = pptxToHtmlPath.Replace("\\", "/").Replace(" ", "");
htmlPath = pptxToHtmlPath;
if (!DirFileHelper.IsExistFile(pptxToHtmlPath))
{
//转换成html
DirFileHelper.CreateFileContent(pptxToHtmlPath, string.Empty);
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
filePreviewIBLL.ConvertPptxToHtml(data[0].F_FilePath, pptxToHtmlPath);
}
else
{
Directory.Delete(tempDirectory, true);
//转换成html
DirFileHelper.CreateFileContent(pptxToHtmlPath, string.Empty);
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
filePreviewIBLL.ConvertPptxToHtml(data[0].F_FilePath, pptxToHtmlPath);
}
}
return htmlPath;
}
#endregion
#region 将Pdf文档转换为图片
///
/// 将Pdf文档转换为图片
///
/// 附件夹主键
///
public List ConvertToImg(string folderId)
{
List listSplitUrl = new List();
List data = annexesFileIBLL.GetEntitys(folderId);
if (data != null && data.Count > 0)
{
string directoryName = data[0].F_FileName.Split('.')[0].Replace(" ", "");//获取选择文件名称
string pptPath = data[0].F_FilePath; //路径
string pdfPath = pptPath.Substring(0, pptPath.LastIndexOf(".")) + ".pdf";//pdf文件名
if (!DirFileHelper.IsExistFile(pdfPath))
{
FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL();
filePreviewIBLL.GetPptData(pptPath);
}
PDFFile pdfFile = PDFFile.Open(pdfPath);
string vdir = "";
string imgPath = Config.GetValue("ConvertPptxToImg");
UserInfo userInfo = LoginUserInfo.Get();
// vdir = UserId/汇报文件ID/年月日/文件名称
vdir = "{1}/{2}/{3}/{4}";
vdir = string.Format(vdir, userInfo.userId, folderId, DateTime.Now.ToString("yyyyMMdd"), directoryName);
imgPath = Path.Combine(imgPath, vdir);
imgPath = imgPath.Replace("\\", "/").Replace(" ", "");
if (!Directory.Exists(imgPath))
{
Directory.CreateDirectory(imgPath);
}
else
{
Directory.Delete(imgPath, true);
Directory.CreateDirectory(imgPath);
}
for (int i = 1; i <= pdfFile.PageCount; i++)
{
Bitmap pageImage = pdfFile.GetPageImage(i - 1, 56 * (int)5);
vdir = string.Format("{0}{1}.jpeg", directoryName, i.ToString());
string imgPathTemp = Path.Combine(imgPath, vdir);
imgPathTemp = imgPathTemp.Replace("\\", "/");
EncoderParameters ep = new EncoderParameters();
long[] qy = new long[1];
qy[0] = 10;
EncoderParameter eParam = new EncoderParameter(Encoder.Quality, qy);
ep.Param[0] = eParam;
ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageDecoders();
ImageCodecInfo jpegICIinfo = null;
for (int x = 0; x < arrayICI.Length; x++)
{
if (arrayICI[x].FormatDescription.Equals("JPEG"))
{
jpegICIinfo = arrayICI[x];
break;
}
}
string thumbnail = imgPathTemp.Substring(0, imgPathTemp.LastIndexOf(".")) + ".JPEG";
pageImage.Save(thumbnail, jpegICIinfo, ep);
string str = thumbnail.Split('/')[0];
listSplitUrl.Add(thumbnail.Replace(str, ""));
pageImage.Dispose();
}
pdfFile.Dispose();
}
return listSplitUrl;
}
#endregion
}
}