/// <param name="fileAdress">文件地址</param>
public responseObject UploadFile(string fileAdress)
string postRequestAddress = "post请求地址";
//请求参数 注意这里请求参数中不包括要上传文件的那个请求参数
Dictionary<string, string> RequestParameters = new Dictionary<string, string>();
RequestParameters.Add("请求参数名1", "请求参数值1");
RequestParameters.Add("请求参数名2", "请求参数值2");
string responseStr =HttpPostFile(url + "/api_pc_cashier/" + postRequestAddress, RequestParameters,fileAdress);
responseObject responseObj = JsonConvert.DeserializeObject<responseObject>(responseStr);
/// <param name="Url">服务器地址</param>
/// <param name="postParameter">请求参数</param>
/// <param name="fileAdress">文件地址 </param>
/// <param name="isSuccess"></param>
public static string HttpPostFile(string Url, Dictionary<string, string> RequestParameters, string fileAdress)
FileStream fs = new FileStream(fileAdress, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");
byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); //请求头部信息
StringBuilder sb = new StringBuilder();
foreach (KeyValuePair<string, string> item in RequestParameters)
.Append("Content-Disposition: form-data; name=\"")
.Append(item.Key + "\"").Append("\r\n")
.Append("\r\n").Append(item.Value).Append("\r\n");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append("imgFile");//注意这里是你请求参数中要上传的文件对应的请求参数名称,
sb.Append("\"; filename=\"");
sb.Append("Content-Type: ");
sb.Append("application/octet-stream");
string strPostHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); // 根据uri创建HttpWebRequest对象
HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(Url));
httpReq.Method = "POST"; //对发送的数据不使用缓存
httpReq.AllowWriteStreamBuffering = false; //设置获得响应的超时时间(300秒)
httpReq.Timeout = 300000;
httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;
//long fileLength = fs.Length;
httpReq.ContentLength = length;
byte[] buffer = new byte[bufferLength]; //已上传的字节数
long offset = 0; //开始上传时间
DateTime startTime = DateTime.Now;
int size = r.Read(buffer, 0, bufferLength);
Stream postStream = httpReq.GetRequestStream(); //发送请求头部消息
postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
postStream.Write(buffer, 0, size);
TimeSpan span = DateTime.Now - startTime;
double second = span.TotalSeconds;
size = r.Read(buffer, 0, bufferLength);
postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse webRespon = httpReq.GetResponse();
Stream s = webRespon.GetResponseStream();
StreamReader sr = new StreamReader(s);
String sReturnString = sr.ReadLine();
HttpWebResponse res = (HttpWebResponse)ex.Response;