123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740 |
- /* ==============================================================================
- * 功能描述:UpLoadFileRequest
- * 创 建 者:Garrett
- * 创建日期:2018/3/23 15:19:52
- * ==============================================================================*/
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Windows;
- using SAGA.MBI.Common;
- using Utilities;
- using Aliyun.OSS;
- using Aliyun.OSS.Common;
- using Newtonsoft.Json.Linq;
- using SAGA.DotNetUtils;
- using SAGA.DotNetUtils.Encrypt;
- using SAGA.DotNetUtils.Extend;
- using SAGA.DotNetUtils.FileOperate;
- using SAGA.DotNetUtils.Http;
- using SAGA.DotNetUtils.Logger;
- using SAGA.DotNetUtils.Others;
- using SAGA.MBI.DataArrange;
- using SAGA.MBI.FileStream;
- using SAGA.MBI.JsonConvert;
- using SAGA.MBI.Login;
- using SAGA.MBI.Tools;
- using SAGA.RevitUtils;
- namespace SAGA.MBI.RequestData
- {
- /// <summary>
- /// UpLoadFileRequest
- /// </summary>
- public class UpLoadFileRequest
- {
- /// <summary>
- /// 是否使用oss
- /// </summary>
- /// <returns></returns>
- public static bool UseOss()
- {
- var flag = ConfigurationUtil.Default.GetSettingValue("UpDownFlag");
- return flag==null||flag.Trim() == "0";
- }
- #region Download
- /// <summary>
- /// 下载指定文件到指定
- /// </summary>
- /// <param name="downPath"></param>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static bool DownLoadRevitFile(string downPath, string fileName)
- {
- try
- {
- if (!Directory.Exists(downPath))
- Directory.CreateDirectory(downPath);
- var filePath = Path.Combine(downPath, fileName);
- //如果文件存在,删除重新下载
- File.Delete(filePath);
- //文件下载
- var url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/file_get/{fileName}?systemId={MBIConst.RevitServiceId}";
- WebClient wc = new WebClient();
- wc.Headers.Add("postman-token", "8efb60cb-a34c-592e-6e61-5412b1dfc1bb");
- wc.Headers.Add("cache-control", "no-cache");
- wc.DownloadFile(new Uri(url), filePath);
- wc.Dispose();
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- return false;
- }
- finally
- {
- }
- return true;
- }
- #endregion
- #region DownLoadAsync
-
- private static WinMFMDownloadProcress windown = null;
- public static WinMFMDownloadProcress GetProcessWin()
- {
- return windown;
- }
- /// <summary>
- /// 显示下载窗体
- /// </summary>
- public static void ShowDownloadWindow(string floorName, string fullPath, int count, int cur)
- {
- if (windown == null)
- {
- windown = new WinMFMDownloadProcress();
- windown.Show();
- }
- windown.LabelFloorName = $"正在下载{floorName}层模型文件,请稍后。。。";
- windown.LabelPath = fullPath;
- windown.Count = count;
- windown.Cur = cur;
- }
- /// <summary>
- /// 下载指定文件到指定
- /// </summary>
- /// <param name="downPath"></param>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static bool DownLoadFileAsync(Tuple<string, int, string> tuple, int count, int cur)
- {
- if (!UpLoadFileRequest.UseOss())
- {
- return FileContentTransferUnit.DownLoadFileAsync(tuple, count, cur);
- }
- bool result = true;
- string fullPath = tuple.Item1;
- string floorName = tuple.Item3;
- string cloudName = CommonTool.GetCloudRevitName(fullPath);
- int state = tuple.Item2;
- if (state == 2)
- FloorFileOperate.BakFile(fullPath);
- string key = $"{MBIConst.OssClientFileKey}{cloudName}";
-
- DownLoadNew:
- OssClient client;
- if (WebRequestProxy.IsOnline(out ClientConfiguration conf))
- {
- client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret, conf);
- }
- else
- {
- client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret);
- }
-
- int timeoutNum = 20;
- long totalLength = 0;
- try
- {
- string bucketName = MBIConst.BucketName;
- ShowDownloadWindow(tuple.Item3, fullPath, count, cur);
- var getObjectRequest = new GetObjectRequest(bucketName, key);
- //getObjectRequest.StreamTransferProgress += DownStreamProgressCallback;
- var buffer = new byte[1024 * 1024];
- long stargIndex = 0;
- getObjectRequest.StreamTransferProgress += (s, args) =>
- {
-
- var tempTrans = stargIndex + args.TransferredBytes;
- var tempTotal = stargIndex + args.TotalBytes;
- var currentData = Math.Round(((double)tempTrans)/ tempTotal *100d, 3);
- Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
- Math.Round(tempTotal / 1024d / 1024,3), Math.Round(tempTrans / 1024d / 1024,3), currentData);
- windown?.Update(currentData);
- //currentData >= 100d
- if (tempTrans >= tempTotal && windown!=null&&windown.Count == windown.Cur)
- {
- //MessageBox.Show("数据上传完毕!");
- CloseDownloadWin(true, false);
- }
- };
- using (var fs = new MemoryStream())
- {
- ReDownload:
- getObjectRequest.SetRange(stargIndex, -1);
- OssObject ossObject = client.GetObject(getObjectRequest);
- //设置下载超时时间
- ossObject.ResponseStream.ReadTimeout = 60 * 1000;//*20;
- if (totalLength == 0)
- {
- totalLength = ossObject.ContentLength;
- }
- using (var stream = ossObject.Content)
- {
- var bytesRead = 0;
- try
- {
- while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
- {
- fs.Write(buffer, 0, bytesRead);
- }
- }
- catch (WebException e)
- {
- #region 超时重试
- if (0 < timeoutNum-- && e.Message.Contains("超时"))
- {
- stargIndex = fs.Length;
- //timeoutNum--;
- goto ReDownload;
- }
- throw;
- #endregion
- }
- if (fs.Length < totalLength)
- {
- stargIndex = fs.Length;
- goto ReDownload;
- }
- }
- FileStreamOperate.WriteFile(fs.ToArray(), fullPath);
- #region 下载后Md5较验
- string md5 = MD5Tools.GetMD5HashFromFileByBase64(fullPath);
- //下载后的文件md5校验
- if (client.GetObjectMetadata(bucketName, key).ContentMd5 != md5)
- {
- string per = Math.Round((fs.Length / (double)totalLength) * 100, 3) + "%";
- string errorMessage = ($"楼层 {floorName} MD5校验失败,本地与服务器不一致!下载进度{per}");
- if (fs.Length== totalLength)
- {
- if (MessageShowBase.Question(errorMessage + "\r\n是否重新下载该层文件"))
- {
- goto DownLoadNew;
- }
- }
- else
- {
- MessageShowBase.Infomation(errorMessage);
- }
- MailLog.Log("下载MD5异常", errorMessage);
- result = false;
- }
- #endregion
- }
- Log4Net.Debug($"Get object:{key} succeeded");
- }
- catch (Exception ex)
- {
- MessageShowBase.Infomation("Revit文件下载失败!\r\n"+ex.Message+"\r\n"+ex.StackTrace);
- result = false;
- CloseDownloadWin(result,false);
- }
- return result;
- }
- /// <summary>
- /// 下载进度条
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="args"></param>
- private static void DownStreamProgressCallback(object sender, StreamTransferProgressArgs args)
- {
- try
- {
- var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
- Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
- args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData);
- windown?.Update(currentData);
- if (currentData >= 100d && windown.Count == windown.Cur)
- {
- //MessageBox.Show("数据上传完毕!");
- CloseDownloadWin(true, false);
- }
- }
- catch (Exception ex)
- {
- throw;
- }
- }
- /// <summary>
- /// 关闭下载窗口
- /// </summary>
- public static void CloseDownloadWin(bool issucess, bool hasTip = true)
- {
- if (windown != null)
- {
- windown?.Close();
- windown = null;
- }
- if (hasTip)
- MessageShowBase.Infomation(issucess ? "Revit模型文件下载成功!" : "Revit模型文件下载失败!");
- }
- #endregion
- #region Upload
- /// <summary>
- /// 将本地文件上传到指定的服务器(HttpWebRequest方法)
- /// </summary>
- /// <returns></returns>
- public static string UpLoadFile(string downPath, string fileName, string url)
- {
- var responseValue = string.Empty;
- var filePath = downPath;
- if (!File.Exists(downPath))
- filePath = Path.Combine(downPath, fileName);
- try
- {
- var request = (HttpWebRequest)WebRequest.Create(url);
- request.Timeout = 60000;
- request.Method = "POST";
- //每次上传4k
- int bufferLength = 40960;
- byte[] buffer = new byte[bufferLength];
- // 要上传的文件
- System.IO.FileStream fs = new System.IO.FileStream(filePath, FileMode.Open, FileAccess.Read);
- BinaryReader r = new BinaryReader(fs);
- int size = r.Read(buffer, 0, bufferLength);
- //request.ContentLength = bufferLength;
- Stream postStream = null;
- try
- {
- while (size > 0)
- {
- postStream = request.GetRequestStream();
- postStream.Write(buffer, 0, bufferLength);
- size = r.Read(buffer, 0, bufferLength);
- }
- }
- catch (Exception e)
- {
- Console.WriteLine(e);
- throw;
- }
- finally
- {
- fs.Close();
- postStream?.Close();
- r.Close();
- }
- //返回数据
- using (var response = (HttpWebResponse)request.GetResponse())
- {
- if (response.StatusCode != HttpStatusCode.OK)
- {
- var message = String.Format("Request failed. Received HTTP {0}", response.StatusCode);
- throw new ApplicationException(message);
- }
- // grab the response
- using (var responseStream = response.GetResponseStream())
- {
- if (responseStream != null)
- using (var reader = new StreamReader(responseStream))
- {
- responseValue = reader.ReadToEnd();
- }
- }
- }
- }
- catch (Exception e)
- {
- MessageShowBase.Show(e);
- }
- return responseValue;
- }
- /// <summary>
- /// 上传到文件服务器的Revit目录中
- /// </summary>
- /// <returns></returns>
- public static string UpLoadRevitFile(string downPath, string fileName)
- {
- string systemId = MBIConst.RevitServiceId;
- string secret = MBIConst.RevitServiceSecret;
- //文件下载
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
- return UpLoadFile(downPath, fileName, url);
- }
- /// <summary>
- /// 上传到文件服务器的Dev目录中
- /// </summary>
- /// <returns></returns>
- public static string UpLoadDevFile(string downPath, string fileName)
- {
- string systemId = MBIConst.DevServiceId;
- string secret = MBIConst.DevServiceSecret;
- //文件下载
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
- return UpLoadFile(downPath, fileName, url);
- }
- /// <summary>
- /// 上传到图片服务器的Dev目录中
- /// </summary>
- /// <returns></returns>
- public static string UpLoadDevImage(string downPath, string fileName)
- {
- string systemId = MBIConst.DevServiceId;
- string secret = MBIConst.DevServiceSecret;
- //文件下载
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/image_upload?systemId={systemId}&secret={secret}&key={fileName}&overwrite=true";
- return UpLoadFile(downPath, fileName, url);
- }
- #endregion
- #region UploadAsync
- private static WinMFMUploadProcress win = null;
- public static WinMFMUploadProcress GetUpProcessWin()
- {
- return win;
- }
- /// <summary>
- /// 显示上传窗体
- /// </summary>
- /// <param name="filePath"></param>
- public static void ShowUploadWindow(string floorName, string filePath, int count, int cur)
- {
- if (win == null)
- {
- win = new WinMFMUploadProcress();
- win.Show();
- }
- win.FloorName = $"正在上传{floorName}层模型文件,请稍后。。。";
- win.LabelPath = filePath;
- win.Count = count;
- win.Cur = cur;
- }
- /// <summary>
- /// 关闭上传窗体
- /// </summary>
- public static void CloseUploadWindow(bool issucess, bool hasTip = false)
- {
- if (win != null)
- {
- win?.Close();
- win = null;
- }
- if (hasTip)
- MessageBox.Show(issucess ? "Revit模型文件上传成功!" : "Revit文件上传失败!");
- }
- /// <summary>
- /// 上传Revit文件到服务器
- /// </summary>
- /// <param name="filePath"></param>
- /// <param name="fileName"></param>
- /// <returns></returns>
- public static bool UpLoadRevitAsync(string floorName, string filePath, string fileName, int count, int cur)
- {
- if (!UpLoadFileRequest.UseOss())
- {
- return FileContentTransferUnit.UpLoadRevitAsync(floorName, filePath, fileName,count,cur);
- }
- bool result = true;
- string key = $"{MBIConst.OssClientFileKey}{fileName}";
- OssClient client = new OssClient(MBIConst.Endpoint, MBIConst.AccessKeyId, MBIConst.AccessKeySecret);
- try
- {
- using (var fs = new MemoryStream(FileStreamOperate.ReadFile(filePath)))
- {
- string bucketName = MBIConst.BucketName;
- var putObjectRequest = new PutObjectRequest(bucketName, key, fs);
- ShowUploadWindow(floorName, filePath, count, cur);
- putObjectRequest.StreamTransferProgress += StreamProgressCallback;
- client.PutObject(putObjectRequest);
- #region 上传后MD5较验
- string md5 = MD5Tools.GetMD5HashFromFileByBase64(filePath);
- //上传后的文件md5校验
- if (client.GetObjectMetadata(bucketName, key).ContentMd5 != md5)
- {
- string errorMessage = ($"楼层 {floorName} MD5校验失败,本地与服务器不一致!");
- MailLog.Log("上传MD5异常", errorMessage);
- MessageShowBase.Infomation(errorMessage);
- //不关闭窗体
- // throw new Exception(errorMessage);
- }
- #endregion
- }
- Console.WriteLine("Put object:{0} succeeded", key);
- }
- catch (Exception ex)
- {
- MessageShowBase.Infomation("Revit文件上传载失败!\r\n" + ex.Message + "\r\n" + ex.StackTrace);
- result = false;
- CloseUploadWindow(result,false);
- }
- return result;
- }
- /// <summary>
- /// 上传进度条
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="args"></param>
- private static void StreamProgressCallback(object sender, StreamTransferProgressArgs args)
- {
- var currentData = Math.Round(args.TransferredBytes * 100d / args.TotalBytes, 3);
- Debug.WriteLine("ProgressCallback - TotalBytes:{0}M, TransferredBytes:{1}M,上传百分比:{2}%",
- args.TotalBytes / 1024 / 1024, args.TransferredBytes / 1024 / 1024, currentData);
- win?.Update(currentData);
- if (currentData >= 100d)
- {
- CloseUploadWindow(true, false);
- }
- }
- #endregion
- #region Del
- /// <summary>
- /// 删除服务器文件
- /// </summary>
- /// <returns></returns>
- public static string DeleteFile(string url, string key)
- {
- //文件下载
- try
- {
- JObject jObject = new JObject();
- JArray keyArray = new JArray();
- keyArray.Add(key);
- jObject.Add("keys", keyArray);
- string postData = jObject.ToString();
- RestClient client = new RestClient(url, HttpVerb.POST, postData);
- string request = client.PostRequest();
- return request;
- }
- catch (Exception e)
- {
- MessageShowBase.Show(e);
- }
- return null;
- }
- /// <summary>
- /// 删除文件服务器Revit目录下的数据
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string DeleteRevitFile(string key)
- {
- string systemId = MBIConst.RevitServiceId;
- string secret = MBIConst.RevitServiceSecret;
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={systemId}&secret={secret}";
- return DeleteFile(url, key);
- }
- /// <summary>
- /// 删除文件服务器Dev目录下的数据
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string DeleteDevFile(string key)
- {
- string systemId = MBIConst.DevServiceId;
- string secret = MBIConst.DevServiceSecret;
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={systemId}&secret={secret}";
- return DeleteFile(url, key);
- }
- /// <summary>
- /// 删除图片服务器Dev目录的图片
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public static string DeleteDevImage(string key)
- {
- string systemId = MBIConst.DevServiceId;
- string secret = MBIConst.DevServiceSecret;
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/images_delete?systemId={systemId}&secret={secret}";
- return DeleteFile(url, key);
- }
- #endregion
- #region 一级底层封装
- /*
- * 1、上传接口:URL,(传路径|传bytes) 系统及Id
- * 2、下载接口:URL,(传路径|返回bytes)
- * 3、返回文件列表:前缀,数量默认
- * 4、删除文件:(列表|单独文件)
- */
- public static bool UploadFile(FileServiceSetting setting, string key, Byte[] bytes)
- {
- try
- {
- string url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/file_upload?systemId={setting.SystemId}&secret={setting.Secret}&key={key}&overwrite=true";
- MemoryStream stream = new MemoryStream(bytes);
- var result = RequestClient.UploadFile(url, stream);
- JObject rj = JObject.Parse(result);
- if (rj["Result"].ToString() == "success")
- {
- return true;
- }
- //结果暂时不处理
- throw new Exception(rj["ResultMsg"].ToString());
- return false;
- }
- catch (Exception e)
- {
- throw;
- }
- }
- public static bool UploadFile(FileServiceSetting setting, string key, string filePath)
- {
- try
- {
- var bytes = File.ReadAllBytes(filePath);
- var result = UploadFile(setting, key, bytes);
- //结果暂时不处理
- return true;
- }
- catch (Exception)
- {
- throw;
- }
- }
- public static byte[] DownloadFile(FileServiceSetting setting, string key)
- {
- var url =
- $"{MBIConst.ImageServiceLocalHost}image-service/common/file_get/{key}?systemId={setting.SystemId}";
- try
- {
- return RequestClient.DownloadFile(url);
- }
- catch (Exception e)
- {
- throw;
- }
- return null;
- }
- public static bool DownloadFile(FileServiceSetting setting, string key, string filePath)
- {
- try
- {
- string parentPath = Directory.GetParent(filePath).FullName;
- if (!Directory.Exists(parentPath))
- Directory.CreateDirectory(parentPath);
- //if (!File.Exists(filePath))
- // File.Create(filePath);
- var reuslt = DownloadFile(setting, key);
- if (reuslt == null)
- throw new Exception("下载文件失败");
- File.WriteAllBytes(filePath, reuslt);
- return true;
- }
- catch (Exception)
- {
- throw;
- }
- }
- /// <summary>
- /// 根据指定前缀获取文件列表
- /// </summary>
- /// <param name="prefix"></param>
- /// <returns></returns>
- public static List<string> GetFiles(FileServiceSetting setting, string prefix)
- {
- List<string> files = new List<string>();
- string url = $"{MBIConst.ImageServiceLocalHost}image-service/common/files_list?systemId={setting.SystemId}&secret={setting.Secret}";
- JObject jObject = new JObject();
- jObject.Add("prefix", prefix);
- var result = RequestClient.Post(url, jObject);
- JObject resultJson = JObject.Parse(result);
- files = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(resultJson["Content"].ToString()) ?? new List<string>();
- return files;
- }
- /// <summary>
- /// 删除传入文件信息
- /// </summary>
- /// <param name="setting"></param>
- /// <param name="inputFiles"></param>
- /// <returns>成功删除的文件</returns>
- public static List<string> DeleteFiles(FileServiceSetting setting, List<string> inputFiles)
- {
- List<string> delFiles = new List<string>();
- if (inputFiles.IsNullOrEmptyExt())
- return delFiles;
- string url = $"{MBIConst.ImageServiceLocalHost}image-service/common/files_delete?systemId={setting.SystemId}&secret={setting.Secret}";
- JObject jObject = new JObject();
- JArray array = new JArray();
- inputFiles.ForEach(s => array.Add(s));
- jObject.Add("keys", array);
- var result = RequestClient.Post(url, jObject);
- JObject resultJson = JObject.Parse(result);
- delFiles = Newtonsoft.Json.JsonConvert.DeserializeObject<List<string>>(resultJson["Content"].ToString()) ?? new List<string>();
- return delFiles;
- }
- public static bool DeleteFile(FileServiceSetting setting, string file)
- {
- var delFile = DeleteFiles(setting, new List<string>() { file })?.FirstOrDefault();
- return delFile == file;
- }
- #endregion
- }
- /// <summary>
- /// 文件服务设置
- /// </summary>
- public class FileServiceSetting
- {
- static FileServiceSetting()
- {
- RevitSetting = new FileServiceSetting() { SystemId = MBIConst.RevitServiceId, Secret = MBIConst.RevitServiceSecret };
- DevSetting = new FileServiceSetting() { SystemId = MBIConst.DevServiceId, Secret = MBIConst.DevServiceSecret };
- }
- /// <summary>
- /// 系统ID
- /// </summary>
- public string SystemId { get; set; } = "";
- /// <summary>
- /// 系统密码
- /// </summary>
- public string Secret { get; set; } = "";
- public static FileServiceSetting RevitSetting { get; private set; }
- public static FileServiceSetting DevSetting { get; private set; }
- }
- }
|