首页 > 学院 > 开发设计 > 正文

C# WinForm 上传图片,文件到服务器的方法Uploader.ashx

2019-11-17 03:00:56
字体:
来源:转载
供稿:网友
C# WinForm 上传图片,文件到服务器的方法Uploader.ashx

网上有很多方案,起初用时,因为对asp.net不太了解,觉得FTP实现不错,可是后来发现,如果机器在域控下,就会有问题。

一年过去了,asp.net也熟悉了,知道Ajax没事应该用ashx,验证码也用ashx,当然这里要说的WinForm上传也应该是ashx了吧,哈哈,先提供简单思路:

接收文件的asp.net是:Uploader.ashx,相关代码:

view plaincopy to clipboardPRint?
  1. <%@WebHandlerLanguage="C#"Class="Uploader"%>
  2. usingSystem;
  3. usingSystem.IO;
  4. usingSystem.Web;
  5. publicclassUploader:IHttpHandler
  6. {
  7. publicvoidProcessRequest(HttpContexthc)
  8. {
  9. foreach(stringfileKeyinhc.Request.Files)
  10. {
  11. HttpPostedFilefile=hc.Request.Files[fileKey];
  12. file.SaveAs(Path.Combine(hc.Server.MapPath("."),file.FileName));
  13. }
  14. }
  15. publicboolIsReusable
  16. {
  17. get{returntrue;}
  18. }
  19. }

发送图片或文件的WinForm.cs 相关代码:

view plaincopy to clipboardprint?
  1. System.Net.WebClientmyWebClient=newSystem.Net.WebClient();
  2. myWebClient.UploadFile("http://www.yongfa365.com/Uploader.ashx","POST","C://WINDOWS//system32//cmd.exe");

OK,完了,这样操作后,再也不用管是不是在域控内了,只要能上网,就能上传。够方便吧。


如果你要批量上传,还有上传后保存在哪个目录等操作可以参考柳永法(yongfa365)'Blog写的:

接收文件的asp.net是:Uploader.ashx,相关代码:

view plaincopy to clipboardprint?
  1. <%@WebHandlerLanguage="C#"Class="Uploader"%>
  2. usingSystem;
  3. usingSystem.IO;
  4. usingSystem.Web;
  5. publicclassUploader:IHttpHandler
  6. {
  7. publicvoidProcessRequest(HttpContexthc)
  8. {
  9. stringNowPath=Path.Combine(hc.Server.MapPath("."),hc.Request["path"]);
  10. if(!Directory.Exists(NowPath))
  11. {
  12. Directory.CreateDirectory(NowPath);
  13. }
  14. foreach(stringfileKeyinhc.Request.Files)
  15. {
  16. HttpPostedFilefile=hc.Request.Files[fileKey];
  17. stringFilePath=Path.Combine(NowPath,file.FileName);
  18. if(File.Exists(FilePath))
  19. {
  20. if(Convert.ToBoolean(hc.Request["overwrite"]))
  21. {
  22. File.Delete(FilePath);
  23. }
  24. else
  25. {
  26. continue;
  27. }
  28. }
  29. file.SaveAs(FilePath);
  30. }
  31. }
  32. publicboolIsReusable
  33. {
  34. get{returntrue;}
  35. }
  36. }

发送图片或文件的WinForm.cs 相关代码:

view plaincopy to clipboardprint?
  1. stringurl=@"http://www.yongfa365.com/Uploader.ashx?Overwrite=true&PATH=Logs/"+DateTime.Now.ToString("yyyy-MM-dd");
  2. foreach(stringfileinDirectory.GetFiles(item))
  3. {
  4. System.Net.WebClientmyWebClient=newSystem.Net.WebClient();
  5. myWebClient.UploadFile(url,"POST",file);
  6. }

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表