HTTP协议——HTTPClient类上传
HTTP协议-HTTPClient类-上传
文件上传必须使用POST请求,因为要携带大量的请求内容,而且文件上传必须使用`multipart/form-data`类型的请求体,和之前的`a=1&b=2`、`{"a":1,"b":2}`的写法不太相同。
private async void button2_Click(object sender, EventArgs e)
{
FileStream fs1 = new FileStream("C:/Users/86152/Desktop/测试03.mp4", FileMode.Open); // 第一个文件流
FileStream fs2 = new FileStream("C:/Users/86152/Desktop/python.png", FileMode.Open); // 第二个文件流
// 创建表单
var formData = new MultipartFormDataContent()
{
{new StringContent("123"),"username" },//添加数据
{new StringContent("123"),"age" },
{new StreamContent(fs1),"myFilel","lhx.xmind" },// 添加文件流
{new StreamContent(fs2),"myFilel","lhx5.xmind" },
};
var res = await Http.Client.PostAsync("http://192.168.113.74:3000/uploadl", formData); // 请求上传
string data = await res.Content.ReadAsStringAsync(); // 获取响应
Console.WriteLine(data);
}
带进度上传
// 带进度上传
private async void button3_Click(object sender, EventArgs e)
{
// 1 把组员转成文件流
FileStream fs = new FileStream(@"C:\Users\86152\Desktop\测试2.xls", FileMode.Open);
// 2 组织formdatashujv
var formdata = new MultipartFormDataContent();
formdata.Add(new StreamContent(fs), "myFile2", "111.txt");
formdata.Add(new StringContent("123"), "username");
formdata.Add(new StringContent("123"), "age");
// 3 添加上传进度的事件 绑定事件 在事件函数中取出上传的进度
// HttpSendProgres 发送数据的事件
Http.progressMessageHandler.HttpSendProgress += ProgressMessageHandler_HttpSendProgress;
//4 发请求请求资源
var res = await Http.Client.PostAsync("http://192.168.113.74:3000/upload2", formdata);
//5 获取相应
string data = await res.Content.ReadAsStringAsync();
MessageBox.Show(data);
}
private void ProgressMessageHandler_HttpSendProgress(object sender, System.Net.Http.Handlers.HttpProgressEventArgs e)
{
this.Invoke(new Action(() =>
{
this.progressBar1.Value = e.ProgressPercentage;
MessageBox.Show("");
}));
}
原文地址:https://blog.csdn.net/qq_3517289697/article/details/140553818
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!