发布时间:2020-12-20编辑:佚名阅读(1156)
public void PostFile(string action, string file) { //1、数据边界 string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x"); //2、创建HttpWebRequest请求 WebRequest myRequest = WebRequest.Create(action); myRequest.Method = "POST"; //3、设置请求ContentType 和 边界字符(边界字符必须和请求数据体的边界字符一致,否则服务器无法解析) myRequest.ContentType = "multipart/form-data;boundary=" + boundary; //4、添加文件数据描述信息 StringBuilder sb = new StringBuilder(); sb.Append("--" + boundary); sb.Append("\r\n"); //name 为 上传文件的input name sb.Append("Content-Disposition: form-data; name=file; filename=\"" + file + "\""); sb.Append("\r\n"); sb.Append("Content-Type: application/octet-stream"); //此处则为模拟的文件类型,实际情况下浏览器会根据本地文件后缀名判断此类型 sb.Append("\r\n\r\n"); Encoding encoding = Encoding.UTF8; //此处编码须与网页编码一直,否则导致中文路径或文件名乱码,但文件内容不会乱码 byte[] form_data = encoding.GetBytes(sb.ToString()); //5、表尾数据 byte[] foot_data = encoding.GetBytes("\r\n--" + boundary + "--\r\n"); //6、读取文件 using (FileStream fileStream = new FileStream(file, FileMode.Open, FileAccess.Read)) { StringBuilder sb2 = new StringBuilder(); sb2.Append("--" + boundary); sb2.Append("\r\n"); sb2.Append("Content-Disposition: form-data; name=username;\r\n"); //发送的内容标题 sb2.Append("\r\n"); sb2.Append("中文名称"); //发送的内容 sb2.Append("\r\n"); //每一组数据结束都需要添加换行字符 sb2.Append("--" + boundary); sb2.Append("\r\n"); sb2.Append("Content-Disposition: form-data; name=pwd;\r\n"); sb2.Append("\r\n"); sb2.Append("QADSFDSFA"); sb2.Append("\r\n"); byte[] data = encoding.GetBytes(sb2.ToString()); //6、设置上传数据长度为表头 + 文件 + 表尾长度 myRequest.ContentLength = form_data.Length + foot_data.Length + fileStream.Length + data.Length; //7、得到请求的数据流 Stream requestStream = myRequest.GetRequestStream(); //8.1、将字符信息数据写入请求流 requestStream.Write(data, 0, data.Length); //8.2、将文件信息数据写入请求流 requestStream.Write(form_data, 0, form_data.Length); //9、循环读取文件流 并写入请求流 byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)fileStream.Length))]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } //10、将结束边界数据写入请求流 requestStream.Write(foot_data, 0, foot_data.Length); } //11、发起请求 WebResponse myResponse = myRequest.GetResponse(); //12、读取请求返回的数据流 StreamReader sr = new StreamReader(myResponse.GetResponseStream(), encoding); string json = sr.ReadToEnd().Trim(); MessageBox.Show(json); }
1人
0人
1人
0人