C# WebClient实现文件上传
一、同步上传
文章 https://www.cnblogs.com/duanjt/p/6420172.html 里面有提到服务端通过WebApi如何实现文件上传,这里就只说客户端使用WebClient上传,直接上代码:
private void button2_Click(object sender, EventArgs e) { try { string url = "http://localhost:29817/api/values/SaveFile"; if (string.IsNullOrEmpty(this.textBox1.Text)) { MessageBox.Show("请先选择要上传的文件"); return; } string fileName = this.textBox1.Text;//文件全路径(e:\abc.txt) string safeFileName = Path.GetFileName(fileName);//文件名(abc.txt) WebClient client = new WebClient(); client.Credentials = CredentialCache.DefaultCredentials; client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data client.QueryString["fname"] = safeFileName; byte[] fileb = client.UploadFile(new Uri(url), "POST", fileName); string res = Encoding.UTF8.GetString(fileb); MessageBox.Show(res); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
注意:
1.Header的Content-Type必须设置为application/form-data
二、异步上传
上面是同步方式上传,下面是异步方式上传
private void button2_Click(object sender, EventArgs e) { try { string url = "http://localhost:29817/api/values/SaveFile"; if (string.IsNullOrEmpty(this.textBox1.Text)) { MessageBox.Show("请先选择要上传的文件"); return; } string fileName = this.textBox1.Text;//文件全路径(e:\abc.txt) string safeFileName = Path.GetFileName(fileName);//文件名(abc.txt) WebClient client = new WebClient(); //定义事件,上传成功事件和上传进度事件 client.UploadFileCompleted += client_UploadFileCompleted; client.UploadProgressChanged += client_UploadProgressChanged; client.Credentials = CredentialCache.DefaultCredentials; client.Headers.Add("Content-Type", "application/form-data");//注意头部必须是form-data client.QueryString["fname"] = safeFileName; //异步上传,通过事件回调获取运行状态 client.UploadFileAsync(new Uri(url), "POST", fileName); } catch (Exception ex) { MessageBox.Show("错误:"+ex.Message); } } //上传进度事件,修改进度条 void client_UploadProgressChanged(object sender, UploadProgressChangedEventArgs e) { progressBar1.Minimum = 0; progressBar1.Maximum = (int)e.TotalBytesToSend; progressBar1.Value = (int)e.BytesSent; progressBar1.Text = e.ProgressPercentage.ToString(); } //上传完成事件,判断是否上传成功 void client_UploadFileCompleted(object sender, UploadFileCompletedEventArgs e) { if (e.Error == null) { progressBar1.Value = progressBar1.Maximum; this.label2.Text = "上传成功."; } else { MessageBox.Show("上传错误:" + e.Error.Message); this.label2.Text = "上传失败."; } }
说明:
1.上传的方法由UploadFile修改为UploadFileAsync,这个方法是异步的,非阻塞。
2.注册WebClient的两个事件UploadFileCompleted和UploadProgressChanged,用于显示进度。
三、大文件上传
大文件传输
1.服务端web.config需要配置最大的请求:
<configuration> <system.web> <httpRuntime targetFramework="4.5" maxRequestLength="2147483647" /> </system.web> <system.webServer> <security> <requestFiltering> <requestLimits maxAllowedContentLength="2147483647"/> </requestFiltering> </security> </system.webServer> </configuration>
2.WebApi代码
[HttpPost]
public String SaveFile()
{
var request = HttpContext.Current.Request;
if (request.Files.Count > 0)
{
HttpPostedFile file= request.Files.Get(0);
file.SaveAs(Path.Combine("E:", file.FileName));
}
return "1";
}
备注:
1.一般配置为最大2G差不多了,如果比2G还大,建议使用FTP上传吧。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗