using Face.Domain.Application.FaceAll; using Face.Domain.Entities; using Face.Domain.ViewModels; using Face.Services.DBUtility.Common; using Face.Services.Manager; using Face.Web.Areas.App.Models; using MySql.Data.MySqlClient; using Newtonsoft.Json.Linq; using SqlSugar; using System; using System.Collections.Generic; using System.Data; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Net; using System.Net.Security; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Hosting; using System.Web.Mvc; namespace Face.Web.Areas.App.Controllers { public class ImgServerController : Controller { // GET: App/ImgServer public JsonResult Update() { try { string TimePath = HostingEnvironment.MapPath("~/Upload/Image/");//保存路径 TimePath += DateTime.Now.ToString("yyyy-MM-dd"); TimePath += "\\"; var oFile = Request.Files[0];//获得上传的文件 //获取后缀名 string ext = Path.GetExtension(Request.Files[0].FileName); //string fullPath = Guid.NewGuid().ToString() + ext; string fullPath = DateTime.Now.ToString("yyyy-MM-dd HH-mm-ss fff") + ext; if (!Directory.Exists(TimePath))//判断文件夹是否存在 { Directory.CreateDirectory(TimePath);//不存在则创建文件夹 } oFile.SaveAs(TimePath + fullPath); //int c = oFile.ContentLength;//字节长度 FileInfo file = new FileInfo(TimePath + fullPath); string imgUrl = TimePath + fullPath; string UPUrl = HostingEnvironment.MapPath("~/Upload/Imgs/");//压缩后保存路径 string littleUrl = HostingEnvironment.MapPath("~/Upload/Img/");//压缩后保存路径 if (!Directory.Exists(UPUrl))//判断文件夹是否存在 { Directory.CreateDirectory(UPUrl);//不存在则创建文件夹 } string ur;//传递URL给前端 //long size; //缩略图 Task taskOne = MakeThumbnail(imgUrl, littleUrl, 85, 85, "Cut"); //using (FileStream fs = new FileStream(file.ToString(), FileMode.OpenOrCreate, FileAccess.Read)) //{ // Image objImage = Image.FromStream(fs); // ImageFormat imFormat = objImage.RawFormat; // MemoryStream memoryStream = Zip(objImage, imFormat, 250, fs.Length); // Image img = Image.FromStream(memoryStream); // img.Save(UPUrl + file.Name); // size = memoryStream.Length; // //异步压缩图 // string ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image"; // Task task = FtpUpload(UPUrl + fullPath, ftpURL); // task.Start(); // ur = task.Result; //} Task tasktwo = MakeThumbnail(imgUrl, UPUrl, 500, 500, ""); tasktwo.Start(); //异步压缩图 string ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image"; Task task = FtpUpload(tasktwo.Result, ftpURL); task.Start(); ur = task.Result; taskOne.Start(); string urltwo = taskOne.Result; string ftpURLTwo = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/Img"; Task taskTwo = FtpUpload(urltwo, ftpURLTwo); taskTwo.Start(); ur = taskTwo.Result; var data1 = new { src = ur //,sizes = size }; var Person = new { code = 0,//0表示成功 msg = "",// data = data1 }; return Json(Person);// } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } } public JsonResult UpdateYh() { try { string TimePath = ""; string ftpURL = ""; var type =int.Parse(Request.Form["type"]);//获得上传的类型 var houseid= int.Parse(Request.Form["houseid"]);//获得酒店id var roomid = int.Parse(Request.Form["roomid"]);//获得房间id var remark = Request.Form["remark"];//获得备注 switch (type) { case 1: TimePath = HostingEnvironment.MapPath("~/Upload/firmware/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/FW"; break; case 2: TimePath = HostingEnvironment.MapPath("~/Upload/Logo/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/Logo"; break; case 3: TimePath = HostingEnvironment.MapPath("~/Upload/backgroundImage/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/BkgPng"; break; } TimePath += DateTime.Now.ToString("yyyy-MM-dd"); TimePath += "\\"; var oFile = Request.Files[0];//获得上传的文件 string fullPath = Request.Files[0].FileName; if (!Directory.Exists(TimePath))//判断文件夹是否存在 { Directory.CreateDirectory(TimePath);//不存在则创建文件夹 } string ur;//传递URL给前端 oFile.SaveAs(TimePath + fullPath); FileInfo file = new FileInfo(TimePath + fullPath); string Url = TimePath + fullPath; Task task = FtpUpload(Url, ftpURL); task.Start(); ur = task.Result; fileawholelog flie=new fileawholelog(); flie.filename = fullPath; flie.hotelid = houseid; flie.type = 1; flie.filetype = type; flie.remark = remark; flie.creationtime = DateTime.Now; flie.roomid = roomid; using (SqlSugarClient db = SqlSugarBase.GesmartDb()) { db.Insertable(flie).ExecuteCommand(); } return Json(new { data = "", status = true }); } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return Json(new { data = e.Message, status = false }); } } public JsonResult judgeUpdate() { try { string TimePath = ""; string ftpURL = ""; var type = int.Parse(Request.Form["type"]);//获得上传的类型 var houseid = int.Parse(Request.Form["houseid"]);//获得酒店id var remark = Request.Form["remark"];//获得备注 switch (type) { case 1: TimePath = HostingEnvironment.MapPath("~/Upload/firmware/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/FW"; break; case 2: TimePath = HostingEnvironment.MapPath("~/Upload/Logo/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/Logo"; break; case 3: TimePath = HostingEnvironment.MapPath("~/Upload/backgroundImage/");//保存路径 ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/BkgPng"; break; } string time = FileImageHy("ftp://" + ftpURL + "/" + Request.Files[0].FileName); if (time==null) { return Json("ture"); } else { return Json("false"); } } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } } /// /// 图片上传到ftp(异步) /// /// 源文件路径 public Task FtpUpload(string filename, string ftpServerIP) { string ftpUserID = "uts_manager";//ftp账号 string ftpPassword = "uts_Inhaos@all";//ftp密码 FileInfo fileInf = new FileInfo(filename); FtpWebRequest reqFTP; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { // 根据uri创建FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = true; //如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true。如果不写会报出421错误(服务不可用) reqFTP.EnableSsl = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型 reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为 10kb int buffLength = 10480; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的buffLength kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入 upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); return new Task(() => fileInf.Name); } catch (Exception ex) { Response.Write("Upload Error:" + ex.Message); } } catch (Exception e) { Response.Write("Upload Error:" + e.Message); } return null; } /// /// 图片上传到ftp(同步) /// /// 源文件路径 public string FtpUploadsyn(string filename, string ftpServerIP) { string ftpUserID = "uts_manager";//ftp账号 string ftpPassword = "uts_Inhaos@all";//ftp密码 FileInfo fileInf = new FileInfo(filename); FtpWebRequest reqFTP; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { // 根据uri创建FtpWebRequest对象 reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name)); // ftp用户名和密码 reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword); // 默认为true,连接不会被关闭 // 在一个命令之后被执行 reqFTP.KeepAlive = true; //如果要连接的 FTP 服务器要求凭据并支持安全套接字层 (SSL),则应将 EnableSsl 设置为 true。如果不写会报出421错误(服务不可用) reqFTP.EnableSsl = false; // 指定执行什么命令 reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型 reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小 reqFTP.ContentLength = fileInf.Length; // 缓冲大小设置为 10kb int buffLength = 10480; byte[] buff = new byte[buffLength]; int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件 FileStream fs = fileInf.OpenRead(); try { // 把上传的文件写入流 Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的buffLength kb contentLen = fs.Read(buff, 0, buffLength); // 流内容没有结束 while (contentLen != 0) { // 把内容从file stream 写入 upload stream strm.Write(buff, 0, contentLen); contentLen = fs.Read(buff, 0, buffLength); } // 关闭两个流 strm.Close(); fs.Close(); return fileInf.Name; } catch (Exception ex) { Response.Write("Upload Error:" + ex.Message); } } catch (Exception e) { Response.Write("Upload Error:" + e.Message); } return null; } /// /// 从oyl_FTP/ftp获取图片 /// /// 路径 /// //public ActionResult FileImage(string url, string ftp = "") //{ // //Logs.WriteLog("222获取图片开始"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); // if (ftp != "") // { // //url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; // url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; // } // else // { // //url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Img/" + url; // url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; // } // FtpWebRequest ftpWeb; // try // { // ServicePointManager.ServerCertificateValidationCallback = // new RemoteCertificateValidationCallback(ValidateServerCertificate); // try // { // ftpWeb = (FtpWebRequest)FtpWebRequest.Create(url);//创建ftp连接 // ftpWeb.Credentials = new NetworkCredential("uts_manager", "uts_Inhaos@all");//账号,密码 // ftpWeb.KeepAlive = false; // ftpWeb.EnableSsl = false; // ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile; // ftpWeb.UseBinary = true; // ftpWeb.UsePassive = true; // //AUTS.Services.Manager.Logs.WriteLog("获取图片数据开始" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); // WebResponse ftpResponse = (FtpWebResponse)ftpWeb.GetResponse(); // //AUTS.Services.Manager.Logs.WriteLog("获取图片数据结束" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); // Stream ftpStream = ftpResponse.GetResponseStream();//获取图片流 // MemoryStream outstream = new MemoryStream();//转成MS流 // int bufferLen = 4096;//缓冲区 // byte[] buffer = new byte[bufferLen]; // int count = 0; // while ((count = ftpStream.Read(buffer, 0, bufferLen)) > 0) // { // outstream.Write(buffer, 0, count); // } // //var img = outstream.ToArray(); // //Logs.WriteLog(img.ToString()); // var img = outstream.ToArray(); // ftpResponse.Close(); // ftpStream.Close(); // outstream.Close(); // return File(img, "image/jpeg");//转成图片格式 // //return new Task(() => outstream.ToArray()); // } // catch (Exception e) // { // LogHelp.WriteExceptionLog(e, this.GetType().Name); // return null; // } // } // catch (Exception ex) // { // LogHelp.WriteExceptionLog(ex, this.GetType().Name); // return null; // } //} public ActionResult FileImage(string url, string ftp = "") { //Logs.WriteLog("222获取图片开始"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); if (ftp != "") { //url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; } else { //url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Img/" + url; url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/Image/" + url; } FtpWebRequest ftpWeb; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { ftpWeb = (FtpWebRequest)FtpWebRequest.Create(url);//创建ftp连接 ftpWeb.Credentials = new NetworkCredential("uts_manager", "uts_Inhaos@all");//账号,密码 ftpWeb.KeepAlive = false; ftpWeb.EnableSsl = false; ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile; ftpWeb.UseBinary = true; ftpWeb.UsePassive = true; //AUTS.Services.Manager.Logs.WriteLog("获取图片数据开始" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); WebResponse ftpResponse = (FtpWebResponse)ftpWeb.GetResponse(); //AUTS.Services.Manager.Logs.WriteLog("获取图片数据结束" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); Stream ftpStream = ftpResponse.GetResponseStream();//获取图片流 MemoryStream outstream = new MemoryStream();//转成MS流 int bufferLen = 4096;//缓冲区 byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = ftpStream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } //var img = outstream.ToArray(); //Logs.WriteLog(img.ToString()); var img = outstream.ToArray(); ftpResponse.Close(); ftpStream.Close(); outstream.Close(); return File(img, "image/jpeg");//转成图片格式 //return new Task(() => outstream.ToArray()); } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } } catch (Exception ex) { LogHelp.WriteExceptionLog(ex, this.GetType().Name); return null; } } public object YHFileImage(string url) { //Logs.WriteLog("222获取图片开始"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); url = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/" + url; FtpWebRequest ftpWeb; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { ftpWeb = (FtpWebRequest)FtpWebRequest.Create(url);//创建ftp连接 ftpWeb.Credentials = new NetworkCredential("uts_manager", "uts_Inhaos@all");//账号,密码 ftpWeb.KeepAlive = false; ftpWeb.EnableSsl = false; ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile; ftpWeb.UseBinary = true; ftpWeb.UsePassive = true; //AUTS.Services.Manager.Logs.WriteLog("获取图片数据开始" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); WebResponse ftpResponse = (FtpWebResponse)ftpWeb.GetResponse(); //AUTS.Services.Manager.Logs.WriteLog("获取图片数据结束" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); Stream ftpStream = ftpResponse.GetResponseStream();//获取图片流 MemoryStream outstream = new MemoryStream();//转成MS流 int bufferLen = 4096;//缓冲区 byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = ftpStream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } //var img = outstream.ToArray(); //Logs.WriteLog(img.ToString()); var img = outstream.ToArray(); ftpResponse.Close(); ftpStream.Close(); outstream.Close(); return File(img, "image/jpeg"); //return new Task(() => outstream.ToArray()); } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } } catch (Exception ex) { LogHelp.WriteExceptionLog(ex, this.GetType().Name); return null; } } /// /// 从am_FTP/ftp获取图片 /// /// 路径 /// public ActionResult FileImage2(string url, string ftp = "") { //Logs.WriteLog("222获取图片开始"+DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); if (ftp != "") { url = "ftp://uts-svr2.qicp.net:50/uts_Manager/am_FTP/Image/" + url; } else { url = "ftp://uts-svr2.qicp.net:50/uts_Manager/am_FTP/Img/" + url; } FtpWebRequest ftpWeb; try { ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { ftpWeb = (FtpWebRequest)FtpWebRequest.Create(url);//创建ftp连接 ftpWeb.Credentials = new NetworkCredential("uts_manager", "uts_Inhaos@all");//账号,密码 ftpWeb.KeepAlive = false; ftpWeb.EnableSsl = true; ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile; ftpWeb.UseBinary = true; ftpWeb.UsePassive = true; //AUTS.Services.Manager.Logs.WriteLog("获取图片数据开始" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); WebResponse ftpResponse = (FtpWebResponse)ftpWeb.GetResponse(); //AUTS.Services.Manager.Logs.WriteLog("获取图片数据结束" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); Stream ftpStream = ftpResponse.GetResponseStream();//获取图片流 MemoryStream outstream = new MemoryStream();//转成MS流 int bufferLen = 4096;//缓冲区 byte[] buffer = new byte[bufferLen]; int count = 0; while ((count = ftpStream.Read(buffer, 0, bufferLen)) > 0) { outstream.Write(buffer, 0, count); } //var img = outstream.ToArray(); //Logs.WriteLog(img.ToString()); var img = outstream.ToArray(); ftpResponse.Close(); ftpStream.Close(); outstream.Close(); return File(img, "image/jpeg");//转成图片格式 //return new Task(() => outstream.ToArray()); } catch (Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } } catch (Exception ex) { LogHelp.WriteExceptionLog(ex, this.GetType().Name); return null; } } /// ///判断是否有文件(移海人脸机ftp) /// /// /// /// public string FileImageHy(string url) { try { FtpWebRequest ftpWeb; ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(ValidateServerCertificate); try { ftpWeb = (FtpWebRequest)FtpWebRequest.Create(url);//创建ftp连接 ftpWeb.Credentials = new NetworkCredential("uts_manager", "uts_Inhaos@all");//账号,密码 ftpWeb.KeepAlive = false; ftpWeb.EnableSsl = false; ftpWeb.Method = WebRequestMethods.Ftp.DownloadFile; ftpWeb.UseBinary = true; ftpWeb.UsePassive = true; //AUTS.Services.Manager.Logs.WriteLog("获取图片数据开始" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); FtpWebResponse ftpResponse = (FtpWebResponse)ftpWeb.GetResponse(); //AUTS.Services.Manager.Logs.WriteLog("获取图片数据结束" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss fff")); DateTime fileTimestamp = ftpResponse.LastModified; ftpResponse.Close(); return fileTimestamp.ToString(); } catch (Exception e) { return null; } } catch (WebException) { return null; } } /// /// 获取文件列表(移海人脸机ftp) /// /// public List GetFilesList(string filepath) { string ftpUrl = "ftp://auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/"+ filepath + "/"; string username = "uts_manager"; string password = "uts_Inhaos@all"; List fileList = new List(); try { // 创建FTP请求 FtpWebRequest request = (FtpWebRequest)WebRequest.Create(ftpUrl); request.Method = WebRequestMethods.Ftp.ListDirectoryDetails; request.Credentials = new NetworkCredential(username, password); // 发送FTP请求并获取响应 FtpWebResponse response = (FtpWebResponse)request.GetResponse(); System.IO.Stream responseStream = response.GetResponseStream(); System.IO.StreamReader reader = new System.IO.StreamReader(responseStream); string line = reader.ReadLine(); while (line != null) { // 解析文件属性行 string[] tokens = line.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries); string permissions = tokens[0]; string fileSize = tokens[4]; string fileName = ""; if (tokens.Length > 9) { for (int i = 8; i < tokens.Length; i++) { //Andrey 3x4.jpg if (i== tokens.Length) { fileName += tokens[i]; } else { fileName += tokens[i] + " "; } } } else { fileName = tokens[tokens.Length - 1]; } // 获取文件的详细属性 FtpWebRequest fileRequest = (FtpWebRequest)WebRequest.Create(ftpUrl + fileName); fileRequest.Method = WebRequestMethods.Ftp.GetDateTimestamp; fileRequest.Credentials = new NetworkCredential(username, password); FtpWebResponse fileResponse = (FtpWebResponse)fileRequest.GetResponse(); DateTime fileCreationTime = fileResponse.LastModified; FileDetails file = new FileDetails(fileName, fileSize, fileCreationTime); fileList.Add(file); line = reader.ReadLine(); } // 关闭资源 reader.Close(); response.Close(); return fileList; } catch (Exception ex) { return null ; } } /// /// 无证书时跳过不报错 /// /// /// /// /// /// public static bool ValidateServerCertificate (object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; } /// /// 压缩图片至n Kb以下 /// /// 图片 /// 图片格式 /// 压缩后大小 /// 原始大小 /// 压缩后的图片内存流 public static MemoryStream Zip(Image img, ImageFormat format, long targetLen, long srcLen = 0) { //设置允许大小偏差幅度 默认10kb const long nearlyLen = 10240; //返回内存流 如果参数中原图大小没有传递 则使用内存流读取 var ms = new MemoryStream(); if (0 == srcLen) { img.Save(ms, format); srcLen = ms.Length; } //单位 由Kb转为byte 若目标大小高于原图大小,则满足条件退出 targetLen *= 1024; if (targetLen >= srcLen) { ms.SetLength(0); ms.Position = 0; img.Save(ms, format); return ms; } //获取目标大小最低值 var exitLen = targetLen - nearlyLen; //初始化质量压缩参数 图像 内存流等 var quality = (long)Math.Floor(100.00 * targetLen / srcLen); var parms = new EncoderParameters(1); //获取编码器信息 ImageCodecInfo formatInfo = null; var encoders = ImageCodecInfo.GetImageEncoders(); foreach (ImageCodecInfo icf in encoders) { if (icf.FormatID == format.Guid) { formatInfo = icf; break; } } //使用二分法进行查找 最接近的质量参数 long startQuality = quality; long endQuality = 100; quality = (startQuality + endQuality) / 2; while (true) { //设置质量 parms.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality); //清空内存流 然后保存图片 ms.SetLength(0); ms.Position = 0; } } #region 缩略图 /// /// 生成缩略图 /// /// 源图路径(物理路径) /// 缩略图路径(物理路径) /// 缩略图宽度 /// 缩略图高度 /// 生成缩略图的方式 public Task MakeThumbnail(string originalImagePath, string thumbnailPath, int width, int height, string mode) { ReturnResult result = new ReturnResult(); FileInfo info = new FileInfo(originalImagePath); Image originalImage = Image.FromFile(originalImagePath); int towidth = width; int toheight = height; int x = 0; int y = 0; int ow = originalImage.Width; int oh = originalImage.Height; if (mode == "") { if (ow > oh) { mode = "W"; } else { mode = "H"; } } switch (mode) { case "HW"://指定高宽缩放(可能变形) break; case "W"://指定宽,高按比例 toheight = originalImage.Height * width / originalImage.Width; break; case "H"://指定高,宽按比例 towidth = originalImage.Width * height / originalImage.Height; break; case "Cut"://指定高宽裁减(不变形) if ((double)originalImage.Width / (double)originalImage.Height > (double)towidth / (double)toheight) { oh = originalImage.Height; ow = originalImage.Height * towidth / toheight; y = 0; x = (originalImage.Width - ow) / 2; } else { ow = originalImage.Width; oh = originalImage.Width * height / towidth; x = 0; y = (originalImage.Height - oh) / 2; } break; default: break; } //新建一个bmp图片 Image bitmap = new System.Drawing.Bitmap(towidth, toheight); //新建一个画板 Graphics g = System.Drawing.Graphics.FromImage(bitmap); //设置高质量插值法 g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High; //设置高质量,低速度呈现平滑程度 g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; //清空画布并以透明背景色填充 g.Clear(Color.Transparent); //在指定位置并且按指定大小绘制原图片的指定部分 g.DrawImage(originalImage, new Rectangle(0, 0, towidth, toheight), new Rectangle(x, y, ow, oh), GraphicsUnit.Pixel); try { if (!Directory.Exists(thumbnailPath)) { Directory.CreateDirectory(thumbnailPath); } //以jpg格式保存缩略图 bitmap.Save(thumbnailPath + "1" + info.Name); CompressImage(thumbnailPath + "1" + info.Name, thumbnailPath + info.Name); return new Task(() => thumbnailPath + info.Name); //return thumbnailPath + info.Name; } catch (System.Exception e) { LogHelp.WriteExceptionLog(e, this.GetType().Name); return null; } finally { originalImage.Dispose(); bitmap.Dispose(); g.Dispose(); } } #endregion /// /// 无损压缩图片 /// /// 原图片地址 /// 压缩后保存图片地址 /// 压缩质量(数字越小压缩率越高)1-100 /// 压缩后图片的最大大小 /// 是否是第一次调用 /// public static bool CompressImage(string originalFileFullName, string afterConversionFileFullName, int flag = 90, int size = 100, bool isFirst = true) { Image iSource = Image.FromFile(originalFileFullName); ImageFormat tFormat = iSource.RawFormat; //如果是第一次调用,原始图像的大小小于要压缩的大小,则直接复制文件,并且返回true FileInfo firstFileInfo = new FileInfo(originalFileFullName); if (firstFileInfo.Length < size * 1024) { firstFileInfo.CopyTo(afterConversionFileFullName); return true; } int dHeight = iSource.Height;// / 2; int dWidth = iSource.Width;/// 2; int sW = dWidth, sH = dHeight; //按比例缩放 Size tem_size = new Size(iSource.Width, iSource.Height); //if (tem_size.Width > dHeight || tem_size.Width > dWidth) //{ // if ((tem_size.Width * dHeight) > (tem_size.Width * dWidth)) // { // sW = dWidth; // sH = (dWidth * tem_size.Height) / tem_size.Width; // } // else // { // sH = dHeight; // sW = (tem_size.Width * dHeight) / tem_size.Height; // } //} //else //{ // sW = tem_size.Width; // sH = tem_size.Height; //} Bitmap ob = new Bitmap(dWidth, dHeight); Graphics g = Graphics.FromImage(ob); g.Clear(Color.WhiteSmoke); g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality; g.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality; g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; g.DrawImage(iSource, new Rectangle(0, 0, sW, sH), 0, 0, iSource.Width, iSource.Height, GraphicsUnit.Pixel); g.Dispose(); //以下代码为保存图片时,设置压缩质量 EncoderParameters ep = new EncoderParameters(); long[] qy = new long[1]; qy[0] = flag;//设置压缩的比例1-100 EncoderParameter eParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, qy); ep.Param[0] = eParam; try { ImageCodecInfo[] arrayICI = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegICIinfo = null; for (int x = 0; x < arrayICI.Length; x++) { if (arrayICI[x].FormatDescription.Equals("JPEG")) { jpegICIinfo = arrayICI[x]; break; } } if (jpegICIinfo != null) { ob.Save(afterConversionFileFullName, jpegICIinfo, ep); FileInfo fi = new FileInfo(afterConversionFileFullName); if (fi.Length > 1024 * size) { var str = afterConversionFileFullName.Split('.').ToList(); var path = str.LastOrDefault(); path = HostingEnvironment.MapPath($"~/Upload/Image/{new Random().Next()}{DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss")}.{path}"); ob.Save(path, jpegICIinfo, ep); //flag = flag - 10; return CompressImage(path, afterConversionFileFullName, flag, size, false); } //else //{ // ob.Save(afterConversionFileFullName, jpegICIinfo, ep); //} } else { ob.Save(afterConversionFileFullName, tFormat); } return true; } catch (Exception ex) { // 2025 06 21 修改XU---- ob.Save(originalFileFullName, tFormat); LogHelp.WriteExceptionLog(ex); return true; // -----------XU-------- /*LogHelp.WriteExceptionLog(ex); return false;*/ } finally { iSource.Dispose(); ob.Dispose(); //不是第一次就删除源文件 if (!isFirst) { System.IO.File.Delete(originalFileFullName); } } } private string uploadDir; public ImgServerController() { uploadDir = Path.Combine(HttpRuntime.AppDomainAppPath, @"Upload\firmware"); } [HttpPost] public ActionResult UploadChunk(HttpPostedFileBase file, int chunkIndex, int totalChunks, string fileName) { if (file != null && file.ContentLength > 0) { string filePath = Path.Combine(uploadDir, fileName + "." + chunkIndex); using (var outputStream = new FileStream(filePath, FileMode.Create)) { using (var inputStream = file.InputStream) { inputStream.CopyTo(outputStream); } } return Json(new { success = true }); } return Json(new { success = false }); } /// /// 上传固件 /// /// 固件名称 /// 固件大小 /// 固件备注 /// [HttpPost] public ActionResult MergeChunks(string fileName, int totalChunks,string remark) { string finalFilePath = Path.Combine(uploadDir, fileName); using (var mergedFileStream = new FileStream(finalFilePath, FileMode.Create)) { for (int i = 0; i < totalChunks; i++) { string chunkFilePath = Path.Combine(uploadDir, fileName + "." + i); //使用byte读取本地文件 byte[] chunkBytes = System.IO.File.ReadAllBytes(chunkFilePath); mergedFileStream.Write(chunkBytes, 0, chunkBytes.Length); } } byte[] bytearr = System.IO.File.ReadAllBytes(finalFilePath); byte[] aa= MD5.Create().ComputeHash(bytearr); string strmd5 = ""; int toBase = 16; foreach (byte b in aa) { strmd5 += Convert.ToString(b, toBase); } // 清除临时文件块 for (int i = 0; i < totalChunks; i++) { string chunkFilePath = Path.Combine(uploadDir, fileName + "." + i); System.IO.File.Delete(chunkFilePath); } // 执行保存FTP处理逻辑 string ftpURL = "auth.blv-oa.com:50/uts_Manager/oyl_FTP/YH/FW"; Task task = FtpUpload(finalFilePath, ftpURL); task.Start(); string ur = task.Result; System.IO.File.Delete(finalFilePath); DateTime time = DateTime.Now; //string selectsql = string.Format("SELECT * FROM `fileawholelog` where filename='{0}'", fileName); //DataSet asas =DbHelperMySQL.Query(selectsql); List bd = SqlSugarBase.Db.Queryable().Where(x => x.filetype == 1 && x.filename== fileName).ToList(); if (bd.Count==0) { string sql = string.Format("INSERT into fileawholelog(filename,MD5,creationtime,filetype,type,remark,firmwaresize)VALUES('{0}','{1}','{2}',1,1,'{3}',{4})", fileName, strmd5, time, remark, totalChunks); DbHelperMySQL.ExecuteSql(sql); } return Json(new { success = true }); } /// /// 图像水平翻转 /// /// 原来图像 /// //public static Bitmap HorizontalFlip(Bitmap bmp) //{ // try // { // var width = bmp.Width; // var height = bmp.Height; // Graphics g = Graphics.FromImage(bmp); // Rectangle rect = new Rectangle(0, 0, width, height); // bmp.RotateFlip(RotateFlipType.RotateNoneFlipX); // g.DrawImage(bmp, rect); // return bmp; // } // catch (Exception ex) // { // return bmp; // } //} //public static Bitmap Base64StringToImage(string strbase64) //{ // try // { // byte[] arr = Convert.FromBase64String(strbase64); // MemoryStream ms = new MemoryStream(arr); // Bitmap bmp = new Bitmap(ms); // ms.Close(); // return HorizontalFlip(bmp); // } // catch (Exception ex) // { // return null; // } //} } }