/// <summary> /// 获取用户头像 /// </summary> /// <param name="userId">用户ID</param> public void GetImg(string userId) { UserEntity entity = GetEntityByUserId(userId); string img = ""; string fileHeadImg = Config.GetValue("fileHeadImg"); if (entity != null) { if (!string.IsNullOrEmpty(entity.F_HeadIcon)) { string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, entity.F_UserId, entity.F_HeadIcon); if (DirFileHelper.IsExistFile(fileImg)) { img = fileImg; } } } else { img = string.Format("{0}/{1}", fileHeadImg, "on-boy.jpg"); } if (string.IsNullOrEmpty(img)) { if (entity.F_Gender == 0) { img = string.Format("{0}/{1}", fileHeadImg, "on-girl.jpg"); } else { img = string.Format("{0}/{1}", fileHeadImg, "on-boy.jpg"); } } FileDownHelper.DownLoadnew(img); }
/// <summary> /// 获取图片 /// </summary> /// <param name="keyValue">主键</param> public void GetImg(string keyValue) { DTImgEntity entity = GetEntity(keyValue); string img = ""; if (entity != null) { if (!string.IsNullOrEmpty(entity.F_FileName)) { string fileHeadImg = Config.GetValue("fileAppDTImg"); string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, entity.F_Id, entity.F_FileName); if (DirFileHelper.IsExistFile(fileImg)) { img = fileImg; FileDownHelper.DownLoadnew(img); return; } } } else { img = "/Content/images/add.jpg"; } if (string.IsNullOrEmpty(img)) { img = "/Content/images/add.jpg"; } FileDownHelper.DownLoad(img); }
/// <summary> /// 获取图片 /// </summary> /// <param name="keyValue">主键</param> public void GetImg(string keyValue) { string img = ""; if (!string.IsNullOrEmpty(keyValue)) { string fileHeadImg = Config.GetValue("fileHealthImg"); //Config.GetValue("fileAppDTImg"); string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, keyValue, ".jpg"); if (DirFileHelper.IsExistFile(fileImg)) { img = fileImg; FileDownHelper.DownLoadnew(img); return; } } else { img = "/Content/images/add.jpg"; } if (string.IsNullOrEmpty(img)) { img = "/Content/images/add.jpg"; } FileDownHelper.DownLoad(img); }
/// <summary> /// 删除实体数据 /// <param name="keyValue">主键</param> /// <summary> /// <returns></returns> public void DeleteEntity(string keyValue) { try { DTImgEntity entity = GetEntity(keyValue); if (entity != null) { if (!string.IsNullOrEmpty(entity.F_FileName)) { string fileHeadImg = Config.GetValue("fileAppDTImg"); string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, entity.F_Id, entity.F_FileName); if (DirFileHelper.IsExistFile(fileImg)) { System.IO.File.Delete(fileImg); } } } dTImgService.DeleteEntity(keyValue); } catch (Exception ex) { if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowBusinessException(ex); } } }
/// <summary>取得图片文件的宽高</summary> /// <param name="srcFile"></param> /// <param name="ww">取得图片的宽度</param> /// <param name="hh">取得图片的高度</param> /// <returns></returns> public static bool Get_Pic_WW_HH(string srcFile, out int ww, out int hh) { string sExt = DirFileHelper.GetFileExtension(srcFile).ToLower(); if (sExt == "gif" || sExt == "jpg" || sExt == "jpeg" || sExt == "bmp" || sExt == "png") { if (srcFile.IndexOf(":") < 0) { srcFile = DirFileHelper.GetMapPath(srcFile); } if (DirFileHelper.IsExistFile(srcFile)) { try { System.Drawing.Image testImage = System.Drawing.Image.FromFile(srcFile); ww = testImage.Width; hh = testImage.Height; testImage.Dispose(); return(true); } catch (Exception ex) { throw ex; } } } ww = 0; hh = 0; return(false); }
/// <summary> /// 获取映射数据 /// </summary> /// <returns></returns> public Dictionary <string, UserModel> GetModelMap() { try { Dictionary <string, UserModel> dic = cache.Read <Dictionary <string, UserModel> >(cacheKey + "dic", CacheId.user); if (dic == null) { dic = new Dictionary <string, UserModel>(); var list = userService.GetAllList(); foreach (var item in list) { UserModel model = new UserModel() { companyId = item.F_CompanyId, departmentId = item.F_DepartmentId, name = item.F_RealName, }; string img = ""; if (!string.IsNullOrEmpty(item.F_HeadIcon)) { string fileHeadImg = Config.GetValue("fileHeadImg"); string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, item.F_UserId, item.F_HeadIcon); if (DirFileHelper.IsExistFile(fileImg)) { img = item.F_HeadIcon; } } if (string.IsNullOrEmpty(img)) { if (item.F_Gender == 0) { img = "0"; } else { img = "1"; } } model.img = img; dic.Add(item.F_UserId, model); cache.Write(cacheKey + "dic", dic, CacheId.user); } } return(dic); } catch (Exception ex) { if (ex is ExceptionEx) { throw; } else { throw ExceptionEx.ThrowBusinessException(ex); } } }
/// <summary> /// 创建XML的根节点 /// </summary> private void CreateXMLElement() { //创建一个XML对象 _xml = new XmlDocument(); if (DirFileHelper.IsExistFile(_filePath)) { //加载XML文件 _xml.Load(this._filePath); } //为XML的根节点赋值 _element = _xml.DocumentElement; }
public string GetTableHtml(string keyValue) { string table = ""; string fileUrl = keyValue.Substring(1);//去除前面的~号 string filePath = Server.MapPath(Request.ApplicationPath + fileUrl); //判断文件是否存在 if (DirFileHelper.IsExistFile(filePath)) { using (StreamReader sr = new StreamReader(filePath, System.Text.Encoding.Default)) { table = sr.ReadToEnd(); } } //string table = @"<table><tr><td rowspan='2'>接触时间率</td><td colspan='4'>体力劳动强度</td></tr><tr><td>I</td><td>II</td><td>III</td><td>IV</td></tr><tr><td>100%</td><td>30</td><td>28</td><td>26</td><td>25</td></tr><tr><td>75%</td><td>31</td><td>29</td><td>28</td><td>26</td></tr><tr><td>50%</td><td>32</td><td>30</td><td>29</td><td>28</td></tr><tr><td>25%</td><td>33</td><td>32</td><td>31</td><td>30</td></tr><tr><td colspan='5'>接触时间率:劳动者在一个工作日内实际接触高温作业的累计时间与8h的比率。</td></tr></table>"; return(table); }
public static T ReadObjectLocal <T>() where T : class { var basePath = CommonHelper.ExePath; var dirPath = Path.Combine(basePath, "LocalData"); if (DirFileHelper.IsExistDirectory(dirPath)) { var fileName = string.Format("local_{0}.json", typeof(T).ToString()); var filePath = Path.Combine(dirPath, fileName); if (DirFileHelper.IsExistFile(filePath)) { var serializedstr = DirFileHelper.ReadFile(filePath); var deserializedobj = JsonConvert.DeserializeObject <T>(serializedstr); return(deserializedobj); } } return(default(T)); }
/// <summary> /// 获取用户头像 /// </summary> /// <param name="userId">用户ID</param> public void GetImg(string userId) { UserEntity entity = GetEntityByUserId(userId); string img = ""; string fileHeadImg = Config.GetValue("fileHeadImg"); if (entity != null) { if (!string.IsNullOrEmpty(entity.F_HeadIcon)) { string fileImg = string.Format("{0}/{1}{2}", fileHeadImg, entity.F_UserId, entity.F_HeadIcon); if (DirFileHelper.IsExistFile(fileImg)) { img = fileImg; } } } else { img = string.Format("{0}/{1}", fileHeadImg, "on-boy.jpg"); } if (string.IsNullOrEmpty(img)) { if (entity.F_Gender == 0) { img = string.Format("{0}/{1}", fileHeadImg, "on-girl.jpg"); } else { img = string.Format("{0}/{1}", fileHeadImg, "on-boy.jpg"); } if (!File.Exists(img)) { img = @"D:\project\LR\力软敏捷开发框架专业版7.0\Code\Learun.Framework V7.0 pro\Learun.Application.Web\Content\images\head\on-boy.jpg"; } } FileDownHelper.DownLoadnew(img); }
/// <summary> /// 文件预览 /// </summary> /// <param name="fileId">文件ID</param> /// <returns></returns> public void PreviewFile(string fileId) { var data = fileInfoBLL.GetEntity(fileId); string filename = Server.UrlDecode(data.F_FileName); //客户端保存的文件名 string filepath = DirFileHelper.GetAbsolutePath(data.F_FilePath); //路径 if (data.F_FileType == "xlsx" || data.F_FileType == "xls") { filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名 if (!DirFileHelper.IsExistFile(filepath)) { filePreviewIBLL.GetExcelData(DirFileHelper.GetAbsolutePath(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(DirFileHelper.GetAbsolutePath(data.F_FilePath)); } } FileStream files = new FileStream(filepath, FileMode.Open); byte[] fileByte = new byte[files.Length]; files.Read(fileByte, 0, fileByte.Length); files.Close(); System.IO.MemoryStream ms = new MemoryStream(fileByte, 0, fileByte.Length); 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": Response.ContentType = "application/pdf"; break; case "docx": Response.ContentType = "application/pdf"; break; case "ppt": Response.ContentType = "application/x-ppt"; break; case "pptx": Response.ContentType = "application/x-ppt"; break; case "xls": Response.ContentType = "application/pdf"; break; case "xlsx": Response.ContentType = "application/pdf"; break; case "pdf": Response.ContentType = "application/pdf"; break; case "txt": Response.ContentType = "text/plain"; break; case "csv": Response.ContentType = ""; break; default: Response.ContentType = "application/pdf"; break; } Response.Charset = "GB2312"; Response.BinaryWrite(ms.ToArray()); }
/// <summary>生成缩略图</summary> /// <param name="srcFile">原图片路径(服务器路径d:\web\upload\100.jpg)</param> /// <param name="decFile">缩略图路径(服务器路径d:\web\upload\100.jpg)</param> /// <param name="iMaxWidth">限制的宽度</param> /// <param name="iMaxHeight">限制的高度</param> /// <param name="highQuality">如果大于0,使用质量控制(50-100)</param> /// <param name="CutType">0=按比例生成宽高,1=固定图片宽高,2=固定背景宽高,图片按比例生成</param> public static void MakeThumbImage(string srcFile, string decFile, int iMaxWidth, int iMaxHeight, int highQuality = 0, int CutType = 0) { #region 取得路径 if (srcFile.IndexOf(":") < 0) { srcFile = DirFileHelper.GetMapPath(srcFile); } if (decFile.IndexOf(":") < 0) { decFile = DirFileHelper.GetMapPath(decFile); } if (!DirFileHelper.IsExistFile(srcFile)) { return; } #endregion //--------------------------------------- #region 原始图片宽高 System.Drawing.Image srcImage = System.Drawing.Image.FromFile(srcFile); int iSrcWidth = srcImage.Width; int iSrcHeight = srcImage.Height; #endregion //--------------------------------------- #region 读取新图片宽高 int toWidth = 0, toHeight = 0, x = 0, y = 0; if (CutType == 1)//固定宽高 { toWidth = iMaxWidth; toHeight = iMaxHeight; } else { //如果原始图,高度大于宽度,按高度缩放,如果宽度大高度按宽度缩放(不变形) //如果图片缩放后,还是比限制大,再进行缩放,直接宽同度都不超过限制 if ((iSrcWidth < iMaxWidth) && (iSrcHeight < iMaxHeight)) { toWidth = iSrcWidth; toHeight = iSrcHeight; } else { if (iSrcHeight > iSrcWidth) { toHeight = iMaxHeight; toWidth = iSrcWidth * iMaxHeight / iSrcHeight; if (toWidth > iMaxWidth) { //toHeight 必须在 toWidth 前 toHeight = toHeight * iMaxWidth / toWidth; toWidth = iMaxWidth; } } else { toHeight = iSrcHeight * iMaxWidth / iSrcWidth; toWidth = iMaxWidth; if (toHeight > iMaxHeight) { //toWidth 必须在 toHeight 前 toWidth = toWidth * iMaxHeight / toHeight; toHeight = iMaxHeight; } } } } #endregion #region 输出 Bitmap bitmap; if (CutType == 2) { //2=固定背景宽高,图片按比例生成 bitmap = new Bitmap(iMaxWidth, iMaxHeight); if (toWidth <= iMaxWidth && toHeight <= iMaxHeight) { x = System.Convert.ToInt16((iMaxWidth - toWidth) / 2); y = System.Convert.ToInt16((iMaxHeight - toHeight) / 2); } else { if (toWidth < toHeight) { x = System.Convert.ToInt16((iMaxWidth - toWidth) / 2); } else { y = System.Convert.ToInt16((iMaxHeight - toHeight) / 2); } } } else { bitmap = new Bitmap(toWidth, toHeight); } Graphics g = Graphics.FromImage(bitmap); //高质量 //g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 //g.Clear(System.Drawing.Color.Transparent); g.Clear(System.Drawing.Color.White); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(srcImage, new Rectangle(x, y, toWidth, toHeight), new Rectangle(0, 0, iSrcWidth, iSrcHeight), GraphicsUnit.Pixel); srcImage.Dispose(); g.Dispose(); try { if (DirFileHelper.GetFileExtension(srcFile) == "png") { bitmap.Save(decFile, System.Drawing.Imaging.ImageFormat.Png); } else//以jpg格式保存缩略图 { //--------------------------------------- //高质量--使用分级图片质量 if (highQuality > 0) { // 以下代码为保存图片时,设置压缩质量 var encoderParams = new EncoderParameters(); var quality = new long[1]; quality[0] = highQuality; //50-100内 var encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象. ImageCodecInfo[] arrayIci = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegIci = null; for (int i = 0; i < arrayIci.Length; i++) { if (arrayIci[i].FormatDescription.Equals("JPEG")) { jpegIci = arrayIci[i]; //设置JPEG编码 break; } } //--------------------------------------- bitmap.Save(decFile, jpegIci, encoderParams); } else { bitmap.Save(decFile, System.Drawing.Imaging.ImageFormat.Jpeg); } } } catch (Exception e) { throw e; } finally { bitmap.Dispose(); } #endregion }
/// <summary>在图片上生成图片水印</summary> /// <param name="srcFile">要添加水印的图片</param> /// <param name="top">上边距 为0时下边距生效</param> /// <param name="bottom">下边距 上边距为0时生效</param> /// <param name="left">左边距 为0时右边距生效</param> /// <param name="right">右边距 左边距为0时生效</param> /// <param name="limitWidth">原图小于该宽度,将不添加水印</param> /// <param name="HighQuality">如果大于0,使用质量控制(50-100)</param> /// <param name="_WaterPicPath">水印图片所在地址,默认:"/images/Water.png"</param> public static void MakeWaterPic(string srcFile, int top = 0, int bottom = 10, int left = 0, int right = 10, int limitWidth = 300, int HighQuality = 0, string _WaterPicPath = "/images/Water.png") { #region 取得图片绝对地址 if (srcFile.IndexOf(":") < 0) { srcFile = DirFileHelper.GetMapPath(srcFile); } if (!DirFileHelper.IsExistFile(srcFile)) { return; } #endregion #region 取得水印图片 //如果是默认水印图片 if (_WaterPicPath == "/images/Water.png") { //则从配置信息里读取水印图片路径 var waterPicPath = ConfigHelper.GetConfigString("WaterPicPath"); if (!string.IsNullOrEmpty(waterPicPath)) { _WaterPicPath = waterPicPath; } } if (_WaterPicPath.IndexOf(":") < 0) { _WaterPicPath = DirFileHelper.GetMapPath(_WaterPicPath); } if (!DirFileHelper.IsExistFile(_WaterPicPath)) { return; } #endregion //--------------------------------------- #region 判断 System.Drawing.Image srcImage = System.Drawing.Image.FromFile(srcFile); System.Drawing.Image watImage = System.Drawing.Image.FromFile(_WaterPicPath); //水印图大于原图或原图小于300,不加水印 if (watImage.Width > srcImage.Width || srcImage.Width < limitWidth) { srcImage.Dispose(); watImage.Dispose(); return; } #endregion //--------------------------------------- #region 位置 int x = 0, y = 0; if (top != 0) { y = top; if (left != 0) { x = left; } else { x = srcImage.Width - watImage.Width - right; } } else if (bottom != 0) { y = srcImage.Height - watImage.Height - bottom; if (left != 0) { x = left; } else { x = srcImage.Width - watImage.Width - right; } } else { //居中 x = srcImage.Width / 2 - watImage.Width / 2; y = srcImage.Height / 2 - watImage.Height / 2; } #endregion //--------------------------------------- #region 保存 Bitmap bitmap = new Bitmap(srcImage); Graphics g = Graphics.FromImage(bitmap); g.DrawImage(watImage, new Rectangle(x, y, watImage.Width, watImage.Height), 0, 0, watImage.Width, watImage.Height, GraphicsUnit.Pixel); srcImage.Dispose(); watImage.Dispose(); g.Dispose(); try { if (DirFileHelper.GetFileExtension(srcFile) == "png") { bitmap.Save(srcFile, System.Drawing.Imaging.ImageFormat.Png); } else//以jpg格式保存缩略图 { //--------------------------------------- //高质量--使用分级图片质量 if (HighQuality > 0) { // 以下代码为保存图片时,设置压缩质量 EncoderParameters encoderParams = new EncoderParameters(); long[] quality = new long[1]; quality[0] = HighQuality; //50-100内 EncoderParameter encoderParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); encoderParams.Param[0] = encoderParam; //获得包含有关内置图像编码解码器的信息的ImageCodecInfo 对象. ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICI = null; for (int i = 0; i < arrayICI.Length; i++) { if (arrayICI[i].FormatDescription.Equals("JPEG")) { jpegICI = arrayICI[i];//设置JPEG编码 break; } } //--------------------------------------- bitmap.Save(srcFile, jpegICI, encoderParams); } else { bitmap.Save(srcFile, System.Drawing.Imaging.ImageFormat.Jpeg); } } } catch (Exception e) { throw e; } finally { bitmap.Dispose(); } #endregion }
/// <summary>生成一条配置记录的图片</summary> /// <param name="vid"></param> /// <returns></returns> public string fix_PicSize(int vid) { //--------------------------------------------------- UploadConfig mC = new UploadConfig(x => x.Id == vid); if (mC.Id != vid) { return("缺少参数:Id!"); } StringBuilder sb = new StringBuilder(); //只修改关联的图片 //string sql = "select Path from UploadFile where Id=" + vid + " and JoinId>0 order by Id"; //修改全部图片(包含非关联) //string sql = "select Path from UploadFile where UploadConfig_Id=" + vid + " order by Id"; //定义要查询出来的列 var list = new List <string>(); list.Add(UploadFileTable.Path); //定义查询条件 var wheres = new List <ConditionHelper.SqlqueryCondition>(); wheres.Add(new ConditionHelper.SqlqueryCondition(ConstraintType.And, UploadFileTable.UploadConfig_Id, Comparison.Equals, vid)); //定义排序 var sort = new List <string>(); sort.Add(UploadFileTable.Id); string[] rs1 = DataTableHelper.GetArrayString(GetDataTable(false, 0, list, 0, 0, wheres, sort), UploadFileTable.Path); if (rs1 != null && rs1.Length > 0) { int ti = rs1.Length; for (int i = 0; i < ti; i++) { string picImg = rs1[i]; string sExt = DirFileHelper.GetFileExtension(picImg).ToLower(); if (picImg.Length > 4 && (sExt == "jpg" || sExt == "png" || sExt == "gif")) { string orgImg = DirFileHelper.GetFilePathPostfix(picImg, "o"); if (!DirFileHelper.IsExistFile(orgImg)) { DirFileHelper.CopyFile(picImg, orgImg); } //原始图存在的情况下,才能生成其它size if (DirFileHelper.IsExistFile(orgImg)) { OneMakeThumbImage(picImg, mC); } else { sb.AppendFormat("原始文件不存在={0}<br />", picImg); } } } } return(sb.ToString()); }
/// <returns>上传成功返回"",并填充 Model.UploadFile</returns> /// <param name="vid">上传配置模块id,即UploadConfig_Id</param> /// <param name="key">随机key</param> /// <param name="userId">上传者id</param> /// <param name="userName">上传者UserName</param> /// <param name="remotePicUrl">远程图片的url地址</param> /// <param name="m_r">Model.UploadFile</param> /// <returns>上传成功返回"",并填充 Model.UploadFile</returns> public string Upload_RemotePic(int vid, string key, int userId, string userName, string remotePicUrl, UploadFile m_r) { #region 检查参数 //--------------------------------------------------- if (vid < 1 || key.Length < 10) { return("缺少参数:key或sid"); } //--------------------------------------------------- #region 检查登陆 m_r.UserId = userId; m_r.UserName = userName; if (m_r.UserId == 0) { return("您的权限不足!"); } #endregion //--------------------------------------------------- UploadConfig mC = Read_UploadConfig(vid); if (mC.Id != vid) { return("缺少参数:UploadConfig_Id!"); } if (mC.IsPost != 1) { return("系统暂时禁止上传文件2!"); } if (mC.IsEditor != 1) { return("非编辑器类别!"); } mC.UploadType_TypeKey = "image"; #endregion //---------------------------------------------- #region 生成暂时目录 string sCfgSavePath = new Uploader().SavePath; string sSavePath = DirFileHelper.FixDirPath(sCfgSavePath + mC.SaveDir) + DateTime.Now.ToString("yyMM") + "/"; if (!DirFileHelper.CheckSaveDir(sSavePath)) { return("SavePath设置不当:" + sSavePath + ", 或权限不足!"); } string sServerDir = sCfgSavePath + "remote/"; if (!DirFileHelper.CheckSaveDir(sServerDir)) { return("ServerDir设置不当:" + sServerDir + ", 或权限不足!"); } //---------------------------------------------- string sSrcName = StringHelper.Left(DirFileHelper.GetFileName(remotePicUrl), 90); string sFileExt = DirFileHelper.GetFileExtension(sSrcName); //因部部分网站不是标准的jpg、gif扩展名,所以修改下面代码 if (sFileExt.Length > 0) { string sAllowed = ",jpg,gif,png,bmp,"; string sExt = "," + sFileExt.ToLower() + ","; if (sAllowed.IndexOf(sExt) == -1) { sFileExt = "jpg"; } } else { sFileExt = "jpg"; } //---------------------------------------------- string sNewFile = DirFileHelper.GetRndFileName("." + sFileExt); if (sServerDir.IndexOf(":") < 0) { sServerDir = DirFileHelper.FixDirPath(DirFileHelper.GetMapPath(sServerDir)); } string sNewRoot = System.IO.Path.Combine(sServerDir, sNewFile); #endregion //---------------------------------------------- #region 到暂时目录 try { var wc = new System.Net.WebClient(); wc.DownloadFile(remotePicUrl, sNewRoot); } catch (Exception ex) { //throw ex; return(ex.Message.ToLower()); } if (!DirFileHelper.IsExistFile(sNewRoot)) { return("上传失败"); } #endregion //---------------------------------------------- #region 判断是否真实图片格式,并取得图片宽高 int ww = 0, hh = 0; if (!Uploader.Get_Pic_WW_HH(sNewRoot, out ww, out hh)) { DirFileHelper.DeleteFile(sNewRoot); return("非法格式!不是图片文件。"); } int iMaxSize = mC.PicSize; long iFileSize = DirFileHelper.GetFileSize(sNewRoot); /* * if (iFileSize > iMaxSize) * { * return "上传文件大小超过了限制.最多上传(" + DirFileHelper.FmtFileSize2(iMaxSize) + ")."; * } */ #endregion #region 把上传的暂时文件复制到相关模块目录中 string sNewPath = sSavePath + sNewFile; string orgImg = DirFileHelper.GetFilePathPostfix(sNewPath, "o"); //复制到原始图 DirFileHelper.CopyFile(sNewRoot, orgImg); //删除暂时上传的图片 DirFileHelper.DeleteFile(sNewRoot); //生成相关缩略图 OneMakeThumbImage(sNewPath, mC); #endregion //---------------------------------------------- #region 保存入数据库 m_r.UploadConfig_Id = mC.Id; m_r.JoinName = mC.JoinName; m_r.JoinId = 0; m_r.UserType = mC.UserType; m_r.UserIp = IpHelper.GetUserIp(); m_r.AddDate = DateTime.Now; m_r.InfoText = ""; m_r.RndKey = key; m_r.Name = sNewFile; m_r.Path = sNewPath; m_r.Src = sSrcName; m_r.Ext = sFileExt; m_r.Size = ConvertHelper.Cint0(iFileSize); m_r.PicWidth = ww; m_r.PicHeight = hh; //保存入数据库 Add_UploadFile(m_r); #endregion //------------------------------------ //上传成功,输出结果 return(""); }
/// <summary>上传文件,并按设置生成缩略图,水印</summary> /// <returns></returns> public bool UploadFile(HttpPostedFile oFile = null) { #region 检查设置 if (!this.IsEnabled) { SendResponse(500, ""); return(false); } if (this.IsChkSrcPost) { if (!RequestHelper.ChkSrcPost()) { SendResponse(501, ""); return(false); } } if (this._savePath.Length < 1) { SendResponse(101, "SavePath未设置"); return(false); } if (oFile == null) { if (this.FilePostName.Length < 1) { SendResponse(101, "filePostName未设置"); return(false); } } this._savePath = DirFileHelper.FixDirPath(_savePath) + DateTime.Now.ToString("yyMM") + "/"; bool isOk = DirFileHelper.CheckSaveDir(this._savePath); if (!isOk) { SendResponse(101, "SavePath设置不当:" + this._savePath + ", 或权限不足!"); return(false); } #endregion //------------------------------------------------ #region 获取文件对象 //获取文件对象 if (oFile == null) { oFile = HttpContext.Current.Request.Files[FilePostName]; } if (oFile == null) { SendResponse(201, ""); return(false); } //------------------------------------------------ //原始文件名; this.SrcName = Path.GetFileName(oFile.FileName); #endregion //------------------------------------------------ #region 检查文件大小 this._fileSize = oFile.ContentLength; //不能上传小于10字节的内容 if (this.SrcName.Length < 3 || this._fileSize < 10) { SendResponse(201, ""); return(false); } //检测文件大小是否超过限制 if (this._fileSize > (this._maxSize * 1024)) { SendResponse(301, ""); return(false); } #endregion //------------------------------------------------ #region 检查文件类型 this.FileExt = Path.GetExtension(this.SrcName).ToLower().TrimStart('.'); if (!checkAllowedExt(this.FileExt)) { SendResponse(202, ""); return(false); } #endregion #region 文件 //上传 string sServerDir = _savePath; if (sServerDir.IndexOf(":") < 0) { sServerDir = DirFileHelper.FixDirPath(DirFileHelper.GetMapPath(sServerDir)); } string sNewFile = ""; //新文件名(系统生成) string sNewRoot = ""; //新文件路径(绝对路径) while (true) { sNewFile = DirFileHelper.GetRndFileName("." + this.FileExt); sNewRoot = System.IO.Path.Combine(sServerDir, sNewFile); if (!DirFileHelper.IsExistFile(sNewRoot)) { try { oFile.SaveAs(sNewRoot); } catch { SendResponse(204, ""); return(false); } break; } } this.NewFile = sNewFile; this.NewPath = _savePath + sNewFile; #endregion //------------------------------------------------ #region 生成缩略图 + 水印 if (this.FileExt == "jpg" || this.FileExt == "png" || this.FileExt == "gif" || this.FileExt == "jpeg" || this.FileExt == "bmp") { #region 取得原始尺寸 try//能取得图片宽高,是真实的图片 { System.Drawing.Image testImage1 = System.Drawing.Image.FromFile(sNewRoot); this.SrcWidth = testImage1.Width; this.SrcHeight = testImage1.Height; testImage1.Dispose(); this.NewWidth = this.SrcWidth; this.NewHeight = this.SrcHeight; } catch { //非法格式,不是真正的图片 DirFileHelper.DeleteFile(sNewRoot); SendResponse(202, ""); return(false); } //------------------------------------------------ //先备份原始图 var tmpPath = ""; tmpPath = System.IO.Path.Combine(sServerDir, DirFileHelper.GetFileNamePostfix(sNewFile, "o")); DirFileHelper.CopyFile(sNewRoot, tmpPath); #endregion if (this._isFixPic || this._isBigPic || this._isMidPic || this._isMinPic) { #region 创建大图 if (this._isBigPic) { tmpPath = System.IO.Path.Combine(sServerDir, DirFileHelper.GetFileNamePostfix(sNewFile, "b")); if (this._bigWidth > 0 && this._bigHeight > 0) { //缩略 MakeThumbImage(sNewRoot, tmpPath, this._bigWidth, this._bigHeight, this._bigQuality, this.CutType); } else//因为不限制宽高,所以直接复制出来就行了 { DirFileHelper.CopyFile(sNewRoot, tmpPath); } //添加水印 if (this.IsWaterPic) { MakeWaterPic(tmpPath); } } #endregion //------------------------------------------------ #region 创建中图 if (this._isMidPic) { tmpPath = System.IO.Path.Combine(sServerDir, DirFileHelper.GetFileNamePostfix(sNewFile, "m")); if (this._midWidth > 0 && this._midHeight > 0) { //缩略图 MakeThumbImage(sNewRoot, tmpPath, this._midWidth, this._midHeight, this._midQuality, this.CutType); } else//因为不限制宽高,所以直接复制出来就行了 { DirFileHelper.CopyFile(sNewRoot, tmpPath); } //添加水印 if (this.IsWaterPic) { MakeWaterPic(tmpPath); } } #endregion //------------------------------------------------ #region 创建小图 if (this._isMinPic) { tmpPath = System.IO.Path.Combine(sServerDir, DirFileHelper.GetFileNamePostfix(sNewFile, "s")); if (this._minWidth > 0 && this._minHeight > 0) { //缩略图 MakeThumbImage(sNewRoot, tmpPath, this._minWidth, this._minHeight, this._minQuality, this.CutType); } else//因为不限制宽高,所以直接复制出来就行了 { DirFileHelper.CopyFile(sNewRoot, tmpPath); } //微型图不用加水印 } #endregion //------------------------------------------------ #region 创建推荐图 if (this._isHotPic) { tmpPath = System.IO.Path.Combine(sServerDir, DirFileHelper.GetFileNamePostfix(sNewFile, "h")); if (this._hotWidth > 0 && this._hotHeight > 0) { //缩略图 MakeThumbImage(sNewRoot, tmpPath, this._hotWidth, this._hotHeight, this._hotQuality, this.CutType); } else//因为不限制宽高,所以直接复制出来就行了 { DirFileHelper.CopyFile(sNewRoot, tmpPath); } //添加水印 if (this.IsWaterPic) { MakeWaterPic(tmpPath); } } #endregion //------------------------------------------------ #region 限制列表图 if (this._isFixPic && this._picWidth > 0 && this._picHeight > 0) { MakeThumbImage(sNewRoot, sNewRoot, this._picWidth, this._picHeight, this._picQuality, this.CutType); } #endregion #region 取得缩放后的图片宽高 try { System.Drawing.Image testImage2 = System.Drawing.Image.FromFile(sNewRoot); this.NewWidth = testImage2.Width; this.NewHeight = testImage2.Height; testImage2.Dispose(); } catch { DirFileHelper.DelPicFile(this.NewPath); SendResponse(202, ""); return(false); } #endregion } //列表图是否加水印 if (DirFileHelper.IsExistFile(sNewRoot) && this.IsWaterPic) { MakeWaterPic(sNewRoot); } } #endregion //上传成功!! return(true); }
/// <summary> /// 文件预览 /// </summary> /// <param name="fileId">文件ID</param> /// <returns></returns> public void PreviewFile(string fileId) { FilePreviewIBLL filePreviewIBLL = new FilePreviewBLL(); var data = annexesFileIBLL.GetEntity(fileId); string filename = data.F_FileName; //客户端保存的文件名 string filepath = data.F_FilePath; //路径 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") { filepath = filepath.Substring(0, filepath.LastIndexOf(".")) + ".pdf";//文件名 if (!DirFileHelper.IsExistFile(filepath)) { filePreviewIBLL.GetPptData(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": Response.ContentType = "application/pdf"; break; case "docx": Response.ContentType = "application/pdf"; break; case "ppt": Response.ContentType = "application/pdf"; break; case "pptx": Response.ContentType = "application/pdf"; break; case "xls": Response.ContentType = "application/pdf"; break; case "xlsx": Response.ContentType = "application/pdf"; break; case "pdf": Response.ContentType = "application/pdf"; break; case "txt": Response.ContentType = "text/plain"; break; case "csv": Response.ContentType = ""; break; default: Response.ContentType = "application/pdf"; break; } Response.Charset = "GB2312"; Response.WriteFile(filepath); //Response.BinaryWrite(ms.ToArray()); }