using Microsoft.Win32; using Newtonsoft.Json; using System; using System.IO; using System.Net; using System.Text; using System.Threading; using System.Windows; namespace FileUploadWpf { /// /// Interaction logic for MainWindow.xaml /// public partial class MainWindow : Window { /// /// 上传的文件路径。 /// private string[] filePaths; /// /// 上传的文件续传点。 /// private long startPoint; private string baseUrl = @"http://localhost:9091/api/services/isas/"; private string relativePath = @"\InspectionItemResult\2020\03-03\测试二_test33_065148\"; public MainWindow() { InitializeComponent(); } /// /// 上传按钮点击事件。 /// /// /// private void button1_Click(object sender, RoutedEventArgs e) { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Multiselect = true; if (openFileDialog.ShowDialog() == true) { this.filePaths = openFileDialog.FileNames; ThreadStart ts = new ThreadStart(ResumeFileThread); Thread t = new Thread(ts); t.Start(); } } public void ResumeFileThread() { this.Dispatcher.Invoke(() => { this.lb_log.Items.Clear(); }); if (this.filePaths != null && this.filePaths.Length > 0) { foreach (string filePath in this.filePaths) { string result = ResumeFile(filePath, relativePath, startPoint, 1024 * 128); this.Dispatcher.Invoke(() => { this.lb_log.Items.Add(filePath + ":" + result); }); } } } public string ResumeFile(string fromFileFullPath, string toRelativePath, long startPoint, int byteCount) { string hostUrl = baseUrl + "InspectionItemResult/FileUpload"; string result = "上传成功!"; byte[] data; string fileName = System.IO.Path.GetFileName(fromFileFullPath); FileStream fs = new FileStream(fromFileFullPath, FileMode.Open, FileAccess.Read); long fileLength = fs.Length; BinaryReader bReader = new BinaryReader(fs); try { #region 续传处理 if (startPoint == fileLength) { result = "文件秒传!"; } if (startPoint >= 1 && startPoint <= fileLength - 1) { fs.Seek(startPoint, SeekOrigin.Current); } #endregion 续传处理 #region 分割文件上传 for (; startPoint <= fileLength - 1; startPoint = startPoint + byteCount) { int step = 0; if (startPoint + byteCount > fileLength) { data = new byte[Convert.ToInt32(fileLength - startPoint)]; bReader.Read(data, 0, Convert.ToInt32(fileLength - startPoint)); step = Convert.ToInt32(fileLength - startPoint); } else { data = new byte[byteCount]; bReader.Read(data, 0, byteCount); step = byteCount; } string contentRange = "bytes " + startPoint + "-" + (startPoint + step) + "/" + fs.Length; RequestEasyResult rst = HttpHelper.HttpPostRequest(hostUrl + "?fileName=" + fileName + "&relativePath=" + toRelativePath, data, contentRange); this.Dispatcher.Invoke(() => { this.tb_filePath.Text = fromFileFullPath + "||" + rst.Message; this.tb_uploadData.Text = (startPoint + step) + "/" + fileLength; }); } #endregion 分割文件上传 } catch (Exception ex) { result = ex.Message; } bReader.Close(); fs.Close(); return result; } public string ResumeFile_old(string fromFileFullPath, string toRelativePath, long startPoint, int byteCount) { string hostUrl = baseUrl + "InspectionItemResult/FileUpload"; string result = "上传成功!"; byte[] data; string fileName = System.IO.Path.GetFileName(fromFileFullPath); WebClient webClient = new WebClient(); FileStream fs = new FileStream(fromFileFullPath, FileMode.Open, FileAccess.Read); long fileLength = fs.Length; BinaryReader bReader = new BinaryReader(fs); try { #region 续传处理 if (startPoint == fileLength) { result = "文件秒传!"; } if (startPoint >= 1 && startPoint <= fileLength - 1) { fs.Seek(startPoint, SeekOrigin.Current); } #endregion 续传处理 #region 分割文件上传 for (; startPoint <= fileLength - 1; startPoint = startPoint + byteCount) { int step = 0; if (startPoint + byteCount > fileLength) { data = new byte[Convert.ToInt32(fileLength - startPoint)]; bReader.Read(data, 0, Convert.ToInt32(fileLength - startPoint)); step = Convert.ToInt32(fileLength - startPoint); } else { data = new byte[byteCount]; bReader.Read(data, 0, byteCount); step = byteCount; } webClient.Headers.Remove(HttpRequestHeader.ContentRange); webClient.Headers.Add(HttpRequestHeader.ContentRange, "bytes " + startPoint + "-" + (startPoint + step) + "/" + fs.Length); byte[] rstBytes = webClient.UploadData(hostUrl + "?fileName=" + fileName + "&relativePath=" + toRelativePath, "POST", data); string rstStr = Encoding.UTF8.GetString(rstBytes); this.Dispatcher.Invoke(() => { this.tb_filePath.Text = fromFileFullPath + "||" + rstStr; this.tb_uploadData.Text = (startPoint + step) + "/" + fileLength; }); } #endregion 分割文件上传 } catch (Exception ex) { result = ex.Message; } bReader.Close(); fs.Close(); return result; } #region /// /// 允许拖拽。 /// /// /// private void Form1_Load(object sender, RoutedEventArgs e) { this.AllowDrop = true; } #endregion } public class HttpHelper { /// /// http请求,POST方式 /// /// 请求连接 /// 请求参数 /// 根据泛型返回响应值 public static T HttpPostRequest(string url, byte[] buffer, string contentRange = null, string accessToken = null) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址 request.Method = "POST"; //request.Accept = "text/html, application/xhtml+xml, */*"; //"text/html, application/xhtml+xml, */*"; request.ContentType = "multipart/form-data"; if (!string.IsNullOrWhiteSpace(contentRange)) request.Headers.Add("Content-Range", contentRange); if (!string.IsNullOrEmpty(accessToken)) request.Headers.Add("Authorization", "Bearer" + " " + accessToken); if (buffer != null) { request.ContentLength = buffer.Length; request.GetRequestStream().Write(buffer, 0, buffer.Length); } return GetResponseValue(request); } catch (Exception ex) { throw ex; } } private static T GetResponseValue(HttpWebRequest request) { try { T rstObj = default(T); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8)) { rstObj = JsonConvert.DeserializeObject(reader.ReadToEnd()); reader.Close(); reader.Dispose(); } response.Close(); return rstObj; } catch (Exception ex) { throw ex; } } } public class RequestEasyResult { private bool _flag; private string _msg; public bool Flag { get { return _flag; } set { _flag = value; } } public string Message { get { return _msg; } set { _msg = value; } } } }