C# 编程WinForm 上传文件到 Asp.Net 的 Web项目
|
admin
2017年3月22日 0:15
本文热度 5338
|
在做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;
- }
在按钮点击时,便会触发提交操作,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 服务器上。
该文章在 2017/3/22 0:15:30 编辑过