在Httpclient 上传文件时 需要显示进度,需要添加 ProgressMessageHandler 在NuGet中添加 引用
Microsoft.AspNet.WebApi.Client 一下是全部代码包括文件上传
private async void button2_Click(object sender, EventArgs e) { HttpClientHandler handler = new HttpClientHandler(); ProgressMessageHandler progressMessageHandler = new ProgressMessageHandler(handler); progressMessageHandler.HttpSendProgress += ProgressMessageHandler_HttpSendProgress; var httpClient = new HttpClient(progressMessageHandler); httpClient.Timeout = Timeout.InfiniteTimeSpan; var url = "http://10.141.40.176:5236/main/Uploadfile"; var content = new MultipartFormDataContent(); content.Add(new StringContent("ulami"), "Department"); content.Add(new StringContent("1"), "taskname"); content.Add(new StringContent("false"), "cover"); // StringContent loginContent = new StringContent("{\"username\":\"admin\",\"password\":\"123456\"}", Encoding.UTF8, "application/json"); var filepath = textBox1.Text;//97.6MB using var fileStream = new FileStream(filepath, FileMode.Open, FileAccess.Read); using var streamContent = new StreamContent(fileStream, 102400); content.Add(streamContent, "file", "测试文件1.ppt"); var response = await httpClient.PostAsync(url, content); var str = await response.Content.ReadAsStringAsync(); textBox2.Text = str; // try // { // //上传服务器的地址(web服务) // string address = "http://10.141.40.176:7245/main/dwj"; // //上传后文件保存的名称 // string saveName = DateTime.Now.ToString("yyyyMMddHHmmss"); // int count = FileUpload.UpLoad_Request(address, filePath, saveName,progressBar1); // if (count > 0) // { // MessageBox.Show("上传文件成功!"); // } // else // { // MessageBox.Show("上传文件失败!"); // } // } // catch (Exception ex) // { // Console.WriteLine(ex.Message); // } } private void ProgressMessageHandler_HttpSendProgress(object sender, HttpProgressEventArgs e) { Console.WriteLine(e.ProgressPercentage + "%"); }
标签:ProgressMessageHandler,StringContent,C#,content,var,new,上传,HttpClient From: https://www.cnblogs.com/lisghxfdfgh/p/17171121.html