①单文件上传(Button点击事件)
1.选择文件上传
OpenFileDialog ofd = new OpenFileDialog();
string name = ofd.FileName;(获取选中文件的名称)
post请求数据数据格式
1:new StringContent("123") 以字符串方式传递服务器,自动设置content-type= text/plain格式
2:new StringContent("{\"name\":\"123\",\"psw\":\"123456\"}", Encoding.UTF8, "application/josn")
以字符串方式传递数据 content-type= application/josn"格式
需要下载System.Net.Http.Json.dll第三方
JsonContent.Create(new People { name="2122",psw="121212"})
3:new FormUrlEncodedContent(new Dictionary<string, string>()
{
{ "name","zs" },
{ "psw","123456" }
})
);自动设置content-type= application/x-www-form-urlencoded 格式
new StringContent("name=zs&psw=123", Encoding.UTF8, "application/x-www-form-urlencoded")
4 new MultipartContent() 上传文件设置数据类型
自动设置content-type= Multipart/formdata格式
2.获取文件流
FileStream fs = new FileStream(name, FileMode.Open);
3.组织表单数据
var formData = new MultipartFormDataContent();
Add添加:formData.Add(new StringContent("123"),"username");
formData.Add(new StringContent("123"), "age");
formData.Add(new StreamContent(fs), "myFile","xzy.png");
4.发请求
string i = "自己的数据库"
HttpResponseMessage res = await Http.Clinet.PostAsync(i,formData);
5 获取响应
string data = await res.Content.ReadAsStringAsync();
Console.WriteLine(data);
②多文件上传
string t = (本地图片位置);
string p = (本地图片位置);
private async void button2_Click(object sender, EventArgs e)
{
FileStream fs1 = new FileStream(@p, FileMode.Open); //第一个文件流
FileStream fs2 = new FileStream(@t, FileMode.Open);
var formData = new MultipartFormDataContent()
{
{new StringContent("123"),"username"},
{ new StringContent("123"),"age"},
{new StreamContent(fs1),"myFile1","(名字).xmind" },
{new StreamContent(fs2),"myFile1","(名字).txt" },
};
var res = await Http.Clinet.PostAsync("http://192.168.113.74:3000/upload1", formData);
res.EnsureSuccessStatusCode();
string data = await res.Content.ReadAsStringAsync();
Console.WriteLine(data);
}
③带进度条的上传(Button点击事件,ProgressBar进度条)
private async void button3_Click(object sender, EventArgs e)
{
//1 把资源转成文件流
FileStream fs = new FileStream(@(本地位置), FileMode.Open);
// 2 组织formdata数据
var formdata = new MultipartFormDataContent();
formdata.Add(new StreamContent(fs), "myFile2", "名字.mp4");
formdata.Add(new StringContent("123"), "username");
formdata.Add(new StringContent("123"), "age");
//3 添加上传进度的事件,绑定事件 在事件函数中取出上传的进度
//HttpSendProgress 发送数据的事件
Http.progressMessageHandler.HttpSendProgress += ProgressMessageHandler_HttpSendProgress;
//4 发请求上传资源
var res = await Http.Clinet.PostAsync("http://192.168.113.74:3000/upload2", formdata);
//5 获取响应
string data = await res.Content.ReadAsStringAsync();
Console.WriteLine(data);
}
private void ProgressMessageHandler_HttpSendProgress(object sender, System.Net.Http.Handlers.HttpProgressEventArgs e)
{
BeginInvoke((Action)(() =>
{
//e.ProgressPercentage; 上传进度
this.progressBar1.Value = e.ProgressPercentage;
}));
}
可以回头看,不要回头走!