using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using HL_FristAidPlatform_DTO; using HL_FristAidPlatform_Public; using Newtonsoft.Json; using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Net; using System.Runtime.InteropServices; using System.Text; using System.Windows.Forms; namespace HL_FristAidPlatform_PreHospitalEmergency { public partial class Form_FileInfo : XtraForm { /// /// 当前页 /// public int curPage = 1; /// /// 每页大小 /// public int pageSize = 100; /// /// 所有记录条数 /// public int totalNumber = 0; public Form_FileInfo() { InitializeComponent(); } const int GB = 1024 * 1024 * 1024;//定义GB的计算常量 const int MB = 1024 * 1024;//定义MB的计算常量 const int KB = 1024;//定义KB的计算常量 private void Form_FileInfo_Load(object sender, EventArgs e) { GetSuffixList(); BindFileInfoDetail(curPage); } /// /// 文件上传 /// /// /// private void sbtn_Upload_Click(object sender, EventArgs e) { try { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.ShowHelp = false;//设置是否显示"帮助"按钮 openFileDialog.InitialDirectory = "C:\\";//设置初始目录为盘 openFileDialog.Title = "选择文件";//设置对话框的标题 openFileDialog.FileName = "";//设置初始选择的文件名为空 openFileDialog.Multiselect = true;//可以多选 if (openFileDialog.ShowDialog() == DialogResult.OK) { string[] strNames = openFileDialog.SafeFileNames; List list = new List(); string webUrl = ConfigurationManager.AppSettings["WebApiUrl"]; string sendFileUrl = webUrl + "api/service/T_Service_FirstAid_FileInfo/MultiFileUpload"; progressBarControl1.Visible = true; progressBarControl1.Properties.Minimum = 0; progressBarControl1.Properties.Maximum = 100; progressBarControl1.Properties.Step = 1; progressBarControl1.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid; progressBarControl1.Position = 0; progressBarControl1.Properties.ShowTitle = true; progressBarControl1.Properties.PercentView = true; for (int i = 0; i < strNames.Length; i++) { T_Service_FirstAid_FileInfoDTO fileDto = new T_Service_FirstAid_FileInfoDTO(); fileDto.CreationTime = DateTime.Now; fileDto.CreationID = Information.User.ID; fileDto.UserName = Information.User.LoginName; fileDto.HospitalGuid = Information.Hospital.GUID; string filePath = strNames[i].Substring(0, strNames[i].IndexOf('.')).ToString(); fileDto.FileName = filePath; FileInfo info = new FileInfo(openFileDialog.FileNames[i]); info.IsReadOnly = true; fileDto.GUID = Guid.NewGuid().ToString(); FileStream fs = new FileStream(openFileDialog.FileNames[i], FileMode.OpenOrCreate, FileAccess.Read); FileStream fileStream = new FileStream(openFileDialog.FileNames[i], FileMode.Open, FileAccess.Read, FileShare.Read); if (info != null && info.Exists) { fileDto.FlieSize = ByteConversionGBMBKB(info.Length); fileDto.Suffix = Path.GetExtension(strNames[i]); byte[] buffer; //音频文件: string[] voideFile = { ".mp3,.wma,.avi,.rm,.rmvb,.flv,.mpg,.mov,.mkv,.cda,.midi,wav" }; bool isContains = voideFile.Contains(fileDto.Suffix); if (isContains) { buffer = new byte[fileStream.Length]; fileStream.Read(buffer, 0, buffer.Length); fileStream.Close(); Stream stream = new MemoryStream(buffer); } else { buffer = new byte[1024 * 1024 * 5]; //返回本次读取到的有效字节数 int iNr = fs.Read(buffer, 0, buffer.Length); //将字节数组中每一个元素按指定编码写成字符串 string str = Encoding.UTF8.GetString(buffer, 0, iNr); fs.Close(); //释放资源 fs.Dispose(); } } else { Console.WriteLine("指定的文件路径不正确!"); } WebClient webClient = new WebClient(); webClient.Headers.Add(HttpRequestHeader.Authorization, "Bearer " + Information.User.Token); webClient.Headers.Add("Content-Type", "application/form-data"); var resultData = webClient.UploadFile(sendFileUrl, openFileDialog.FileNames[i]); string result = Encoding.UTF8.GetString(resultData); MultiFileUploadDTO dto = JsonConvert.DeserializeObject(result); int index = dto.res.Split('\\').Length - 1; fileDto.FileSavePath = webUrl + "UploadFile/" + dto.res.Split('\\')[index]; if (dto.isSuccess == "false") { MessageBox.Show(dto.returnMsg); } else { list.Add(fileDto); } } string url = string.Empty; url = "api/service/T_Service_FirstAid_FileInfo"; ClientFactory httpClient = new HttpClientFactory(); Client client = httpClient.VisitFactory(); var sendData = JsonConvert.SerializeObject(list); //访问 ListEntity t = client.BatchPost(sendData, url); if (t.Success) { BindFileInfoDetail(curPage); for (int j = 0; j < progressBarControl1.Properties.Maximum; j++) { //处理当前消息队列中的所有windows消息 Application.DoEvents(); //执行步长 progressBarControl1.PerformStep(); } BindFileInfoDetail(curPage); } else { XtraMessageBox.Show("保存失败,请稍后重试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } progressBarControl1.Visible = false; BindFileInfoDetail(curPage); GetSuffixList(); } } catch (Exception ex) { MessageBox.Show("错误:" + ex.Message); } } private void sbtn_Find_Click(object sender, EventArgs e) { BindFileInfoDetail(curPage); } /// /// 绑定文件信息列表 /// /// private void BindFileInfoDetail(int curPage) { try { string fileName = txt_FileName.Text; string daID = ""; if (!string.IsNullOrEmpty(lookUpEdit_suffix.Text.ToString())) { daID = this.lookUpEdit_suffix.EditValue.ToString(); } string suffix = ""; if (PublicClass.ToString(lookUpEdit_suffix.EditValue, "") != "-1") { suffix = PublicClass.ToString(lookUpEdit_suffix.EditValue, ""); } string startTime = time_FristTime.TimeValue; string endTime = time_EndTime.TimeValue; FileListEntity dt = DBHelpClass.GetFile(string.Format("api/service/T_Service_FirstAid_FileInfo?hospitalGuid={0}&fileName={1}&suffix={2}&startTime={3}&endTime={4}&pageIndex={5}&pageSize={6}", Information.Hospital.GUID, fileName, suffix, startTime, endTime, curPage, pageSize)); grid_FileInfo.DataSource = dt.Data; gridView1.Appearance.EvenRow.BackColor = Color.FromArgb(245, 245, 245); gridView1.Appearance.OddRow.BackColor = Color.FromArgb(255, 255, 255); gridView1.OptionsView.EnableAppearanceEvenRow = true; gridView1.OptionsView.EnableAppearanceOddRow = true; gridView2.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.True; totalNumber = DBHelpClass.TotalNumber; userControlForPage.RefreshPager(pageSize, totalNumber, curPage); } catch (Exception ex) { PublicClass.WriteErrorLog(this.Text, "绑定数据源:\r\n" + ex); } } private void sbtn_Dowload_Click(object sender, EventArgs e) { int[] rows = gridView2.GetSelectedRows(); if (rows.Length == 0) { MessageBox.Show("请选择至少一条数据"); return; } string savePath = ""; FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择下载路径"; string foldPath = ""; if (dialog.ShowDialog() == DialogResult.OK) { foldPath = dialog.SelectedPath; } else { return; } savePath = foldPath; if (!savePath.EndsWith("/") && !savePath.EndsWith("\\")) { savePath = savePath + "/"; } progressBarControl1.Visible = true; progressBarControl1.Properties.Minimum = 0; progressBarControl1.Properties.Maximum = 100; progressBarControl1.Properties.Step = 1; progressBarControl1.Properties.ProgressViewStyle = DevExpress.XtraEditors.Controls.ProgressViewStyle.Solid; progressBarControl1.Position = 0; progressBarControl1.Properties.ShowTitle = true; progressBarControl1.Properties.PercentView = true; foreach (int r in rows) { string uri = gridView2.GetRowCellValue(r, "FileSavePath").ToString(); string fileName; //被下载的文件名 if (uri.IndexOf("\\") > -1) { fileName = uri.Substring(uri.LastIndexOf("\\") + 1); } else { fileName = uri.Substring(uri.LastIndexOf("/") + 1); } savePath += fileName; //另存为的绝对路径+文件名 WebClient client = new WebClient(); try { client.DownloadFile(uri, savePath); } catch { MessageBox.Show("下载失败"); return; } } for (int j = 0; j < progressBarControl1.Properties.Maximum; j++) { //处理当前消息队列中的所有windows消息 Application.DoEvents(); //执行步长 progressBarControl1.PerformStep(); } progressBarControl1.Visible = false; MessageBox.Show("下载成功"); } public string ByteConversionGBMBKB(Int64 KSize) { if (KSize / GB >= 1)//如果当前Byte的值大于等于1GB return (Math.Round(KSize / (float)GB, 2)).ToString() + "GB";//将其转换成GB else if (KSize / MB >= 1)//如果当前Byte的值大于等于1MB return (Math.Round(KSize / (float)MB, 2)).ToString() + "MB";//将其转换成MB else if (KSize / KB >= 1)//如果当前Byte的值大于等于1KB return (Math.Round(KSize / (float)KB, 2)).ToString() + "KB";//将其转换成KGB else return KSize.ToString();//显示Byte值 } /// /// 打开指定目录下的文件 /// /// 文件地址(包含文件名称) /// public static bool OpenFile(string filePath) { try { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) //windows环境下打开文件 { Process.Start(new ProcessStartInfo("cmd", $"/c start { filePath}") { CreateNoWindow = true, WindowStyle = ProcessWindowStyle.Hidden }); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) //Linux环境下打开文件 { Process.Start("xdg-open", filePath); } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) //Mac环境下打开文件 { Process.Start("open", filePath); } } catch (Exception ex) { return false; } return true; } /// /// 文件类型下拉框数据 /// public void GetSuffixList() { try { DataTable dt = DBHelpClass.GetDate(string.Format("api/service/T_Service_FirstAid_FileInfo/GetSuffixList")); DataTable table = new DataTable(); DataColumn ddc = new DataColumn(); ddc.ColumnName = "Name"; ddc.Caption = "Name"; table.Columns.Add(ddc); DataColumn dnameDc = new DataColumn(); dnameDc.Caption = "Value"; dnameDc.ColumnName = "Value"; table.Columns.Add(dnameDc); foreach (var item in dt.Columns) { DataRow ddr = table.NewRow(); ddr["Name"] = item; ddr["Value"] = item; table.Rows.Add(ddr); } PublicClass.SetLookUpList(lookUpEdit_suffix, table, "Name", "Value", true, "请选择"); } catch (Exception ex) { PublicClass.WriteErrorLog(this.Text, "绑定文件类型:\r\n" + ex); } } /// /// 下载服务器文件至客户端 /// /// 被下载的文件地址 /// 另存放的目录 public void Download(string uri) { string fileName; //被下载的文件名 if (uri.IndexOf("\\") > -1) { fileName = uri.Substring(uri.LastIndexOf("\\") + 1); } else { fileName = uri.Substring(uri.LastIndexOf("/") + 1); } string savePath = ""; FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择下载路径"; string foldPath = ""; if (dialog.ShowDialog() == DialogResult.OK) { foldPath = dialog.SelectedPath; } else { return; } savePath = foldPath; if (!savePath.EndsWith("/") && !savePath.EndsWith("\\")) { savePath+=@"\"; // savePath = savePath; } savePath +=fileName; //另存为的绝对路径+文件名 WebClient client = new WebClient(); try { client.DownloadFile(uri, savePath); } catch (Exception e) { MessageBox.Show("下载失败:" + e.ToString()); return; } MessageBox.Show("下载成功"); } public void DeleteFile(string file, List list) { try { DialogResult dr = XtraMessageBox.Show("确认是否删除", "", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.Yes) { if (System.IO.File.Exists(file)) { System.IO.File.Delete(file); Delete(list); } } else { return; } } catch (Exception ex) { PublicClass.WriteErrorLog(this.Text, "删除:\r\n" + ex); } } public void Delete(List list) { try { string Url = "api/service/T_Service_FirstAid_FileInfo/Delete"; //初始化两个工厂 ClientFactory httpClient = new HttpClientFactory(); Client client = httpClient.VisitFactory(); var sendData = JsonConvert.SerializeObject(list); //访问 ListEntity t = client.BatchPost(sendData, Url); if (t.Success) { XtraMessageBox.Show("删除文件成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); BindFileInfoDetail(curPage); } else { XtraMessageBox.Show("删除文件失败,请稍后重试!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { PublicClass.WriteErrorLog(this.Text, "删除:\r\n" + ex); } } private void sbt_Delete_Click(object sender, EventArgs e) { List list = new List(); int[] rows = gridView2.GetSelectedRows(); if (rows.Length == 0) { MessageBox.Show("请选择至少一条数据"); return; } DialogResult dr = XtraMessageBox.Show("确认是否删除", "", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dr == DialogResult.Yes) { for (int i = 0; i < rows.Length; i++) { string file = gridView2.GetRowCellValue(i, "FileSavePath").ToString(); System.IO.File.Delete(file); T_Service_FirstAid_FileInfoDTO dto = new T_Service_FirstAid_FileInfoDTO(); dto.GUID = gridView2.GetRowCellValue(i, "GUID").ToString(); list.Add(dto); } Delete(list); } else { return; } } //private void repositoryItemButtonEdit_ButtonClick(object sender, ButtonPressedEventArgs e) //{ // string filePath = gridView2.GetFocusedRowCellValue("FileSavePath").ToString(); // switch (e.Button.Caption) // { // case "查看": // OpenFile(filePath); // break; // case "下载": // Download(filePath); // break; // case "删除": // List list = new List(); // T_Service_FirstAid_FileInfoDTO dto = new T_Service_FirstAid_FileInfoDTO(); // string guid = gridView2.GetFocusedRowCellValue("GUID").ToString(); // string file = gridView2.GetFocusedRowCellValue("FileSavePath").ToString(); // dto.GUID = guid; // list.Add(dto); // DeleteFile(file, list); // break; // default: // break; // } //} private void Form_FileInfo_FormClosed(object sender, FormClosedEventArgs e) { this.Dispose(); } private void repositoryItemButtonEdit1_ButtonClick(object sender, ButtonPressedEventArgs e) { string filePath = gridView2.GetFocusedRowCellValue("FileSavePath").ToString(); switch (e.Button.Caption) { case "查看": OpenFile(filePath); break; case "下载": Download(filePath); break; case "删除": List list = new List(); T_Service_FirstAid_FileInfoDTO dto = new T_Service_FirstAid_FileInfoDTO(); string guid = gridView2.GetFocusedRowCellValue("GUID").ToString(); string file = gridView2.GetFocusedRowCellValue("FileSavePath").ToString(); dto.GUID = guid; list.Add(dto); DeleteFile(file, list); break; default: break; } } private void userControlForPage_myPagerEvents(int curPage, int pageSize) { userControlForPage.myPagerEvents += MyPagerEvents; } private void MyPagerEvents(int curPage, int pageSize) { this.curPage = curPage; this.pageSize = pageSize; BindFileInfoDetail(curPage); } private void userControlForPage_exportEvents(bool singlePage) { //userControlForPage.exportEvents += ExportEvents; } } }