多份文件上传效果
实现功能(暂无实现文件上传到数据库,只实现界面上传效果):
上传文件名称展示,上传文件名称展示, 上传进度展示,上传速度展示,单个取消操作,全部取消操作;
界面展示
1,设置时间触发器
/// <summary> /// 时间事件触发文件上传 /// </summary> private void TimeEvents() { System.Timers.Timer timer = new System.Timers.Timer(); timer.Enabled = true; timer.Interval = 1000; //执行间隔时间,单位为毫秒; timer.Start(); timer.Elapsed += new System.Timers.ElapsedEventHandler(UpdateFileEvent); } private void UpdateFileEvent(object sender, System.Timers.ElapsedEventArgs e) { if (this.datUpdateFile.Rows.Count == 0) { return; } GC.Collect(); for (int i = 0; i < this.datUpdateFile.Rows.Count; i++) { if (this.datUpdateFile.Rows[i].Cells[2].Value == null || this.datUpdateFile.Rows[i].Cells[2].Value.ToString() != "0%") { continue; } if (this.datUpdateFile.Rows[i].Cells[2].Value.ToString() == "0%") { if (uploadCompletedList.Count >= 3 || uploadCompletList.Contains(this.datUpdateFile.Rows[i].Cells[1].Value.ToString())) { return; } Console.WriteLine(uploadCompletedList.Count); UpdateFile(i.ToString()); } } }
2,在DataGridView中展示需要显示的文件信息
/// <summary> /// 选择文件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button1_Click(object sender, EventArgs e) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "C:"; openFileDialog1.Filter = "所有文件 (*.*)|*.*"; openFileDialog1.Multiselect = true; openFileDialog1.FilterIndex = 1; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { if (this.datUpdateFile.Rows.Count == 0)//上传全部取消后,fileNameList和uploadCompletList需要清空 { fileNameList.Clear(); uploadCompletList.Clear(); } foreach (var fileName in openFileDialog1.FileNames) { if (fileNameList.Count != 0 && fileNameList.Contains(fileName.Split('\\').LastOrDefault())) { continue; } fileNameList.Add(fileName.Split('\\').LastOrDefault()); additem(fileName, fileName.Split('\\').LastOrDefault(), "0%", "上传准备中...", "取消"); } } } /// <summary> /// 显示DataGridView一行内容 /// </summary> /// <param name="fullFileName">文件全路径</param> /// <param name="fileName">文件名</param> /// <param name="colSpeedProgress">进度</param> /// <param name="colSpeed">速度</param> /// <param name="colOperation">操作</param> public void additem(string fullFileName, string fileName, string colSpeedProgress, string colSpeed, string colOperation) { DataGridViewRow dgvr = new DataGridViewRow(); foreach (DataGridViewColumn c in this.datUpdateFile.Columns) { dgvr.Cells.Add(c.CellTemplate.Clone() as DataGridViewCell); } dgvr.Cells[0].Value = fullFileName; dgvr.Cells[1].Value = fileName; dgvr.Cells[2].Value = colSpeedProgress; dgvr.Cells[3].Value = colSpeed; dgvr.Cells[4].Value = colOperation; this.datUpdateFile.Rows.Add(dgvr); }
3,上传文件逻辑
/// <summary> /// 上传文件 /// </summary> /// <param name="num"></param> private void UpdateFile(object num) { if (this.datUpdateFile.RowCount == 0) { Thread.ResetAbort(); return; } //var basePath = System.AppDomain.CurrentDomain.BaseDirectory; //var allFilePath = basePath + "\\fileDic"; //if (!Directory.Exists(allFilePath)) //{ // Directory.CreateDirectory(allFilePath); //} //string buttonText = this.datUpdateFile.Rows[index].Cells[1].Value.ToString();//获取文件后缀 //string fileName = DateTime.Now.ToString("yyyyMMddHHmmss.") + buttonText.Split('.').LastOrDefault();//重置文件名称 //var filePath = allFilePath + "\\" + fileName; int index = int.Parse(num.ToString()); string allFilePathOld = this.datUpdateFile.Rows[index].Cells[0].Value.ToString();//获取文件后缀 uploadCompletedList.Add(this.datUpdateFile.Rows[index].Cells[1].Value.ToString()); try { // 要上传的文件 FileStream fs = new FileStream(allFilePathOld, FileMode.Open, FileAccess.Read); BinaryReader r = new BinaryReader(fs); long length = fs.Length; //每次上传4k int bufferLength = 4096; byte[] buffer = new byte[bufferLength]; //已上传的字节数 long offset = 0; int size = r.Read(buffer, 0, bufferLength); DateTime startTimeEd = startTime; while (size > 0) { offset += size; DateTime startTimeNow = DateTime.Now; TimeSpan span = DateTime.Now - startTimeEd; double second = span.TotalSeconds; try { if (second > 0.001) { this.datUpdateFile.Rows[index].Cells[3].Value = (size / 1024 / second).ToString("0.00") + "KB/秒"; } this.datUpdateFile.Rows[index].Cells[2].Value = (offset * 100.0 / length).ToString("F2") + "%"; } catch (Exception) { return; } Application.DoEvents(); startTimeEd = startTimeNow; #region 判断是否超时或者弱网 if ((DateTime.Now - startTimeNow).TotalSeconds >= 60) { try { this.datUpdateFile.Rows[index].Cells[2].Value = "上传数据超时,请重试"; } catch (Exception) { } return; } if ((DateTime.Now - startTimeNow).TotalSeconds >= 30 && (DateTime.Now - startTimeNow).TotalSeconds <= 60) { MessageBox.Show("网速为弱网,请耐心等待!"); } #endregion size = r.Read(buffer, 0, bufferLength); } r.Close(); try { uploadCompletedList.Remove(this.datUpdateFile.Rows[index].Cells[1].Value.ToString()); uploadCompletList.Add(this.datUpdateFile.Rows[index].Cells[1].Value.ToString()); } catch (Exception) { return; } } catch (Exception ex) { MessageBox.Show("上传失败,请重新上传"); return; } }
4,取消操作
/// <summary> /// 选中一行中button按钮 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void datUpdateFile_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex >= 0 && e.ColumnIndex == 4) { string buttonText = this.datUpdateFile.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString(); Console.WriteLine(buttonText); string contextValue = this.datUpdateFile.Rows[e.RowIndex].Cells[2].Value.ToString(); if (!(contextValue == "0%" || contextValue == "100.00%")) { return; } fileNameList.Remove(this.datUpdateFile.Rows[e.RowIndex].Cells[1].Value.ToString()); this.datUpdateFile.Rows.RemoveAt(e.RowIndex); } }
PS:如有BUG请见谅;