標籤:winform blog http os 檔案 io for re
網上有很多方案,起初用時,因為對asp.net不太瞭解,覺得FTP實現不錯,可是後來發現,如果機器在域控下,就會有問題。
一年過去了,asp.net也熟悉了,知道ajax沒事應該用ashx,驗證碼也用ashx,當然這裡要說的WinForm上傳也應該是ashx了吧,哈哈,先提供簡單思路:
接收檔案的asp.net是:Uploader.ashx,相關代碼:
view plaincopy to clipboardprint?
- <%@ 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 相關代碼:
view plaincopy to clipboardprint?
- 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,相關代碼:
view plaincopy to clipboardprint?
- <%@ 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 相關代碼:
view plaincopy to clipboardprint?
- 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);
- }