在做WinForm時,需要WinForm同Web進行交互,有時需要進行圖片、文件的上傳操作.
WinForm的代碼如下:
C#代碼
- private void button2_Click(object sender, EventArgs e)
- {
-
-
- string a = MyUploader(this.textBox1.Text.Trim(), @"http://localhost/release/Default.aspx");
-
- MessageBox.Show(a);
- }
-
-
- public static string MyUploader(string strFileToUpload, string strUrl)
- {
- string strFileFormName = "file";
- Uri oUri = new Uri(strUrl);
- string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
-
-
- byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");
-
-
- StringBuilder sb = new StringBuilder();
- sb.Append("--");
- sb.Append(strBoundary);
- sb.Append("\r\n");
- sb.Append("Content-Disposition: form-data; name=\"");
- sb.Append(strFileFormName);
- sb.Append("\"; filename=\"");
- sb.Append(Path.GetFileName(strFileToUpload));
- sb.Append("\"");
- sb.Append("\r\n");
- sb.Append("Content-Type: ");
- sb.Append("application/octet-stream");
- sb.Append("\r\n");
- sb.Append("\r\n");
- string strPostHeader = sb.ToString();
- byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
-
-
- HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri);
- oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
- oWebrequest.Method = "POST";
-
-
- oWebrequest.AllowWriteStreamBuffering = false;
-
-
- FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read);
- long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length;
- oWebrequest.ContentLength = length;
- Stream oRequestStream = oWebrequest.GetRequestStream();
-
-
- oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
-
-
- byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))];
- int bytesRead = 0;
- while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0)
- oRequestStream.Write(buffer, 0, bytesRead);
- oFileStream.Close();
-
-
- oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
- WebResponse oWResponse = oWebrequest.GetResponse();
- Stream s = oWResponse.GetResponseStream();
- StreamReader sr = new StreamReader(s);
- String sReturnString = sr.ReadToEnd();
- Console.WriteLine(sReturnString);
-
- oFileStream.Close();
- oRequestStream.Close();
- s.Close();
- sr.Close();
-
- return sReturnString;
- }
在按鈕點擊時,便會觸發(fā)提交操作,Web的Default.aspx代碼如下:
C#代碼
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
- if (Request.Files.Count > 0)
- {
- try
- {
- HttpPostedFile file = Request.Files[0];
- string filePath = this.MapPath("FileUpload") + "\\" + file.FileName;
- file.SaveAs(filePath);
-
- Response.Write("成功了");
-
- }
- catch (Exception)
- {
-
- Response.Write("失敗了1");
- }
- }
- else
- {
- Response.Write("失敗了2");
- }
-
- Response.End();
- }
- }
這樣,便可以將文件通過winform 上傳到web 服務器上。