MainWindow.xaml.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290
  1. using Microsoft.Win32;
  2. using Newtonsoft.Json;
  3. using System;
  4. using System.IO;
  5. using System.Net;
  6. using System.Text;
  7. using System.Threading;
  8. using System.Windows;
  9. namespace FileUploadWpf
  10. {
  11. /// <summary>
  12. /// Interaction logic for MainWindow.xaml
  13. /// </summary>
  14. public partial class MainWindow : Window
  15. {
  16. /// <summary>
  17. /// 上传的文件路径。
  18. /// </summary>
  19. private string[] filePaths;
  20. /// <summary>
  21. /// 上传的文件续传点。
  22. /// </summary>
  23. private long startPoint;
  24. private string baseUrl = @"http://localhost:9091/api/services/isas/";
  25. private string relativePath = @"\InspectionItemResult\2020\03-03\测试二_test33_065148\";
  26. public MainWindow()
  27. {
  28. InitializeComponent();
  29. }
  30. /// <summary>
  31. /// 上传按钮点击事件。
  32. /// </summary>
  33. /// <param name="sender"></param>
  34. /// <param name="e"></param>
  35. private void button1_Click(object sender, RoutedEventArgs e)
  36. {
  37. OpenFileDialog openFileDialog = new OpenFileDialog();
  38. openFileDialog.Multiselect = true;
  39. if (openFileDialog.ShowDialog() == true)
  40. {
  41. this.filePaths = openFileDialog.FileNames;
  42. ThreadStart ts = new ThreadStart(ResumeFileThread);
  43. Thread t = new Thread(ts);
  44. t.Start();
  45. }
  46. }
  47. public void ResumeFileThread()
  48. {
  49. this.Dispatcher.Invoke(() =>
  50. {
  51. this.lb_log.Items.Clear();
  52. });
  53. if (this.filePaths != null && this.filePaths.Length > 0)
  54. {
  55. foreach (string filePath in this.filePaths)
  56. {
  57. string result = ResumeFile(filePath, relativePath, startPoint, 1024 * 128);
  58. this.Dispatcher.Invoke(() =>
  59. {
  60. this.lb_log.Items.Add(filePath + ":" + result);
  61. });
  62. }
  63. }
  64. }
  65. public string ResumeFile(string fromFileFullPath, string toRelativePath, long startPoint, int byteCount)
  66. {
  67. string hostUrl = baseUrl + "InspectionItemResult/FileUpload";
  68. string result = "上传成功!";
  69. byte[] data;
  70. string fileName = System.IO.Path.GetFileName(fromFileFullPath);
  71. FileStream fs = new FileStream(fromFileFullPath, FileMode.Open, FileAccess.Read);
  72. long fileLength = fs.Length;
  73. BinaryReader bReader = new BinaryReader(fs);
  74. try
  75. {
  76. #region 续传处理
  77. if (startPoint == fileLength)
  78. {
  79. result = "文件秒传!";
  80. }
  81. if (startPoint >= 1 && startPoint <= fileLength - 1)
  82. {
  83. fs.Seek(startPoint, SeekOrigin.Current);
  84. }
  85. #endregion 续传处理
  86. #region 分割文件上传
  87. for (; startPoint <= fileLength - 1; startPoint = startPoint + byteCount)
  88. {
  89. int step = 0;
  90. if (startPoint + byteCount > fileLength)
  91. {
  92. data = new byte[Convert.ToInt32(fileLength - startPoint)];
  93. bReader.Read(data, 0, Convert.ToInt32(fileLength - startPoint));
  94. step = Convert.ToInt32(fileLength - startPoint);
  95. }
  96. else
  97. {
  98. data = new byte[byteCount];
  99. bReader.Read(data, 0, byteCount);
  100. step = byteCount;
  101. }
  102. string contentRange = "bytes " + startPoint + "-" + (startPoint + step) + "/" + fs.Length;
  103. RequestEasyResult rst = HttpHelper.HttpPostRequest<RequestEasyResult>(hostUrl + "?fileName=" + fileName + "&relativePath=" + toRelativePath, data, contentRange);
  104. this.Dispatcher.Invoke(() =>
  105. {
  106. this.tb_filePath.Text = fromFileFullPath + "||" + rst.Message;
  107. this.tb_uploadData.Text = (startPoint + step) + "/" + fileLength;
  108. });
  109. }
  110. #endregion 分割文件上传
  111. }
  112. catch (Exception ex)
  113. {
  114. result = ex.Message;
  115. }
  116. bReader.Close();
  117. fs.Close();
  118. return result;
  119. }
  120. public string ResumeFile_old(string fromFileFullPath, string toRelativePath, long startPoint, int byteCount)
  121. {
  122. string hostUrl = baseUrl + "InspectionItemResult/FileUpload";
  123. string result = "上传成功!";
  124. byte[] data;
  125. string fileName = System.IO.Path.GetFileName(fromFileFullPath);
  126. WebClient webClient = new WebClient();
  127. FileStream fs = new FileStream(fromFileFullPath, FileMode.Open, FileAccess.Read);
  128. long fileLength = fs.Length;
  129. BinaryReader bReader = new BinaryReader(fs);
  130. try
  131. {
  132. #region 续传处理
  133. if (startPoint == fileLength)
  134. {
  135. result = "文件秒传!";
  136. }
  137. if (startPoint >= 1 && startPoint <= fileLength - 1)
  138. {
  139. fs.Seek(startPoint, SeekOrigin.Current);
  140. }
  141. #endregion 续传处理
  142. #region 分割文件上传
  143. for (; startPoint <= fileLength - 1; startPoint = startPoint + byteCount)
  144. {
  145. int step = 0;
  146. if (startPoint + byteCount > fileLength)
  147. {
  148. data = new byte[Convert.ToInt32(fileLength - startPoint)];
  149. bReader.Read(data, 0, Convert.ToInt32(fileLength - startPoint));
  150. step = Convert.ToInt32(fileLength - startPoint);
  151. }
  152. else
  153. {
  154. data = new byte[byteCount];
  155. bReader.Read(data, 0, byteCount);
  156. step = byteCount;
  157. }
  158. webClient.Headers.Remove(HttpRequestHeader.ContentRange);
  159. webClient.Headers.Add(HttpRequestHeader.ContentRange, "bytes " + startPoint + "-" + (startPoint + step) + "/" + fs.Length);
  160. byte[] rstBytes = webClient.UploadData(hostUrl + "?fileName=" + fileName + "&relativePath=" + toRelativePath, "POST", data);
  161. string rstStr = Encoding.UTF8.GetString(rstBytes);
  162. this.Dispatcher.Invoke(() =>
  163. {
  164. this.tb_filePath.Text = fromFileFullPath + "||" + rstStr;
  165. this.tb_uploadData.Text = (startPoint + step) + "/" + fileLength;
  166. });
  167. }
  168. #endregion 分割文件上传
  169. }
  170. catch (Exception ex)
  171. {
  172. result = ex.Message;
  173. }
  174. bReader.Close();
  175. fs.Close();
  176. return result;
  177. }
  178. #region
  179. /// <summary>
  180. /// 允许拖拽。
  181. /// </summary>
  182. /// <param name="sender"></param>
  183. /// <param name="e"></param>
  184. private void Form1_Load(object sender, RoutedEventArgs e)
  185. {
  186. this.AllowDrop = true;
  187. }
  188. #endregion
  189. }
  190. public class HttpHelper
  191. {
  192. /// <summary>
  193. /// http请求,POST方式
  194. /// </summary>
  195. /// <param name="url">请求连接</param>
  196. /// <param name="dicParams">请求参数</param>
  197. /// <returns>根据泛型返回响应值</returns>
  198. public static T HttpPostRequest<T>(string url, byte[] buffer, string contentRange = null, string accessToken = null)
  199. {
  200. try
  201. {
  202. HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);//webrequest请求api地址
  203. request.Method = "POST";
  204. //request.Accept = "text/html, application/xhtml+xml, */*"; //"text/html, application/xhtml+xml, */*";
  205. request.ContentType = "multipart/form-data";
  206. if (!string.IsNullOrWhiteSpace(contentRange))
  207. request.Headers.Add("Content-Range", contentRange);
  208. if (!string.IsNullOrEmpty(accessToken))
  209. request.Headers.Add("Authorization", "Bearer" + " " + accessToken);
  210. if (buffer != null)
  211. {
  212. request.ContentLength = buffer.Length;
  213. request.GetRequestStream().Write(buffer, 0, buffer.Length);
  214. }
  215. return GetResponseValue<T>(request);
  216. }
  217. catch (Exception ex)
  218. {
  219. throw ex;
  220. }
  221. }
  222. private static T GetResponseValue<T>(HttpWebRequest request)
  223. {
  224. try
  225. {
  226. T rstObj = default(T);
  227. HttpWebResponse response = (HttpWebResponse)request.GetResponse();
  228. using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
  229. {
  230. rstObj = JsonConvert.DeserializeObject<T>(reader.ReadToEnd());
  231. reader.Close();
  232. reader.Dispose();
  233. }
  234. response.Close();
  235. return rstObj;
  236. }
  237. catch (Exception ex)
  238. {
  239. throw ex;
  240. }
  241. }
  242. }
  243. public class RequestEasyResult
  244. {
  245. private bool _flag;
  246. private string _msg;
  247. public bool Flag
  248. {
  249. get
  250. {
  251. return _flag;
  252. }
  253. set
  254. {
  255. _flag = value;
  256. }
  257. }
  258. public string Message
  259. {
  260. get
  261. {
  262. return _msg;
  263. }
  264. set
  265. {
  266. _msg = value;
  267. }
  268. }
  269. }
  270. }