123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290 |
- 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
- {
- /// <summary>
- /// Interaction logic for MainWindow.xaml
- /// </summary>
- public partial class MainWindow : Window
- {
- /// <summary>
- /// 上传的文件路径。
- /// </summary>
- private string[] filePaths;
- /// <summary>
- /// 上传的文件续传点。
- /// </summary>
- private long startPoint;
- private string baseUrl = @"http://localhost:9091/api/services/isas/";
- private string relativePath = @"\InspectionItemResult\2020\03-03\测试二_test33_065148\";
- public MainWindow()
- {
- InitializeComponent();
- }
- /// <summary>
- /// 上传按钮点击事件。
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- 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<RequestEasyResult>(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
- /// <summary>
- /// 允许拖拽。
- /// </summary>
- /// <param name="sender"></param>
- /// <param name="e"></param>
- private void Form1_Load(object sender, RoutedEventArgs e)
- {
- this.AllowDrop = true;
- }
- #endregion
- }
- public class HttpHelper
- {
- /// <summary>
- /// http请求,POST方式
- /// </summary>
- /// <param name="url">请求连接</param>
- /// <param name="dicParams">请求参数</param>
- /// <returns>根据泛型返回响应值</returns>
- public static T HttpPostRequest<T>(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<T>(request);
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
- private static T GetResponseValue<T>(HttpWebRequest request)
- {
- try
- {
- T rstObj = default(T);
- HttpWebResponse response = (HttpWebResponse)request.GetResponse();
- using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
- {
- rstObj = JsonConvert.DeserializeObject<T>(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;
- }
- }
- }
- }
|