C# WebClient 的文件上传下载
2024-10-06 18:29:35
上传文件
string path = openFileDialog1.FileName;
WebClient wc = new WebClient();
wc.Credentials = CredentialCache.DefaultCredentials;
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
wc.QueryString["fname"] = openFileDialog1.SafeFileName;
byte[] fileb = wc.UploadFile(new Uri(@"http://192.168.31.37:8977/FileHandler.ashx"), "POST", path);
string res = Encoding.GetEncoding("gb2312").GetString(fileb); //或者
//wc.UploadFileAsync(new Uri(@"http://192.168.31.37:8977/FileHandler.ashx"), "POST", path);
//wc.UploadFileCompleted += (s, es) =>
//{
// MessageBox.Show(Encoding.GetEncoding("gb2312").GetString(es.Result));
//};
服务端处理请求
public class FileHandler : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
try
{
HttpFileCollection files = context.Request.Files;
if (files.Count > )
{
files[].SaveAs(HttpContext.Current.Server.MapPath("files/" + context.Request.QueryString["fname"]));
context.Response.Write("save success!");
}
else
context.Response.Write("hello request!");
}
catch (Exception ex)
{
context.Response.Write("save error!" + ex.Message);
}
} public bool IsReusable
{
get
{
return false;
}
}
}
下载文件
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
string path = folderBrowserDialog1.SelectedPath;
WebClient wc = new WebClient();
//wc.Credentials = CredentialCache.DefaultCredentials;
wc.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string fileUrl = @"http://192.168.31.37:8977/files/多用文本.txt"; wc.DownloadFile(new Uri(fileUrl), string.Format(@"{0}\{1}", path, fileUrl.Substring(fileUrl.LastIndexOf('/') + )));
//或者
wc.DownloadFileCompleted += (s, es) =>
{
MessageBox.Show("下载成功!");
}; wc.DownloadFileAsync(new Uri(fileUrl), string.Format(@"{0}\{1}", path, fileUrl.Substring(fileUrl.LastIndexOf('/') + )));
}
最新文章
- Java 计算数学表达式(字符串解析求值工具)
- codeforces 488A. Giga Tower 解题报告
- JAVA动态加载JAR包的实现
- Silverlight通过Wcf Data Service访问数据库之ADO.NET Entity Framework篇
- 【01】视C++为一个语言联邦
- usb host和usb device
- JS点击按钮弹出窗口
- 批量处理csv格式转换成xls
- LeetCode——TwoSum
- 使用Windows2003的IIS发布网站 - 进阶者系列 - 学习者系列文章
- weka对数据进行预测
- ue4访问php接口
- iOS 之 自动释放池
- [转]亿级Web系统搭建:单机到分布式集群
- HTTP协议中的短轮询、长轮询、长连接和短连接,看到一篇文章有感
- Gradle(一)安装配置
- Codeforces 456A - Laptops
- 子窗口访问父页面iframe中的iframe,top打开的子窗口访问父页面中的iframe中的iframe
- FineReport——JS二次开发(隐藏下拉框控件的倒三角)
- hdu 1080(LCS变形)