private void btUpload_Click(object sender, EventArgs e) { var mpfd = new MultiPartFormData(); var file = new FileStream(tbFile.Text, FileMode.Open); byte[] bb = new byte[file.Length]; file.Read(bb, 0, (int)file.Length); file.Close(); mpfd.AddStreamFile("upload", openFileDialog1.SafeFileName, bb); mpfd.PrepareFormData(); HttpWebRequest request = HttpUtil.SendPost("http://192.168.1.121/terminal/uploadImage.do?LOGIN_KEY=UNVALID", mpfd); string res = HttpUtil.GetResponse(request); MessageBox.Show(res); }
/// <summary> /// 用于上传文件的HTTP请求: /// 例子: /// MultiPartFormData form = new MultiPartFormData(); /// form.AddFormField("devilField", "Oracle编程_沈飞"); /// FileStream file = new FileStream("D:\\精通Oracle10gPlSQL编程.pdf", FileMode.Open); /// byte[] bb = new byte[file.Length]; /// file.Read(bb, 0, (int)file.Length); /// file.Close(); /// form.AddStreamFile("fileUpload", "精通Oracle10gPlSQL编程.pdf", bb); /// form.PrepareFormData(); /// HttpWebRequest request = sendPost(uri, form); /// </summary> /// <param name="uri">http请求的地址</param> /// <param name="form">用于封装http请求的表单</param> /// <returns></returns> public static HttpWebRequest SendPost(string uri, MultiPartFormData form) { HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri); //req.Timeout = 3000; req.Method = "POST"; req.ContentType = "multipart/form-data; boundary=" + form.Boundary; //req.AllowWriteStreamBuffering = false; //不用缓存处理 //req.Timeout = 30000; //断线时间限定30秒 using (Stream reqStream = req.GetRequestStream()) { foreach (var b in form.GetFormData()) { reqStream.WriteByte(b); } reqStream.Close(); } return req; }