C# WinForm 上传图片,文件到服务器的方法Uploader.ashx
2024-09-24 19:07:41
网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题。
一年过去了,asp.net也熟悉了,知道ajax没事应该用ashx,验证码也用ashx,当然这里要说的WinForm上传也应该是ashx了吧,哈哈,先提供简单思路:
接收文件的asp.net是:Uploader.ashx,相关代码:
- <%@ WebHandler Language="C#" Class="Uploader" %>
- using System;
- using System.IO;
- using System.Web;
- public class Uploader : IHttpHandler
- {
- public void ProcessRequest(HttpContext hc)
- {
- foreach (string fileKey in hc.Request.Files)
- {
- HttpPostedFile file = hc.Request.Files[fileKey];
- file.SaveAs(Path.Combine(hc.Server.MapPath("."), file.FileName));
- }
- }
- public bool IsReusable
- {
- get { return true; }
- }
- }
发送图片或文件的WinForm.cs 相关代码:
- System.Net.WebClient myWebClient = new System.Net.WebClient();
- myWebClient.UploadFile("http://www.yongfa365.com/Uploader.ashx", "POST", "C:\\WINDOWS\\system32\\cmd.exe");
OK,完了,这样操作后,再也不用管是不是在域控内了,只要能上网,就能上传。够方便吧。
如果你要批量上传,还有上传后保存在哪个目录等操作可以参考柳永法(yongfa365)'Blog写的:
接收文件的asp.net是:Uploader.ashx,相关代码:
- <%@ WebHandler Language="C#" Class="Uploader" %>
- using System;
- using System.IO;
- using System.Web;
- public class Uploader : IHttpHandler
- {
- public void ProcessRequest(HttpContext hc)
- {
- string NowPath = Path.Combine(hc.Server.MapPath("."), hc.Request["path"]);
- if (!Directory.Exists(NowPath))
- {
- Directory.CreateDirectory(NowPath);
- }
- foreach (string fileKey in hc.Request.Files)
- {
- HttpPostedFile file = hc.Request.Files[fileKey];
- string FilePath = Path.Combine(NowPath, file.FileName);
- if (File.Exists(FilePath))
- {
- if (Convert.ToBoolean(hc.Request["overwrite"]))
- {
- File.Delete(FilePath);
- }
- else
- {
- continue;
- }
- }
- file.SaveAs(FilePath);
- }
- }
- public bool IsReusable
- {
- get { return true; }
- }
- }
发送图片或文件的WinForm.cs 相关代码:
- string url = @"http://www.yongfa365.com/Uploader.ashx?Overwrite=true&PATH=Logs\" + DateTime.Now.ToString("yyyy-MM-dd");
- foreach (string file in Directory.GetFiles(item))
- {
- System.Net.WebClient myWebClient = new System.Net.WebClient();
- myWebClient.UploadFile(url, "POST", file);
- }
最新文章
- Python 学习第十八天 js 正则及其它前端知识
- 优化servlet
- iOS汉字中提取首字母
- BestCoder Round #72
- 对象生命周期及crud操作
- Windows下sqlmap的使用_01
- [DEncrypt] MySecurity--安全加密/Base64/文件加密 (转载)
- mybatis处理单表多表操作以及动态sql和批量操作
- Java的内存管理与内存泄露
- 高级I/O函数(2)-splice函数
- linux去掉svn里记住的用户名密码
- Less基础教程
- 使用visualvm 远程监控 JVM
- Fundebug上线Node.js错误监控啦
- 11.4、Libgdx的音频之录制PCM音效
- angular6 safe url pipe
- java缓存技术的介绍
- HBase Master高可用(HA)
- CSS标准文档流 块级元素和行内元素
- aop postsharp的使用:在方法进入/成功/失败/退出时获取方法名和参数值