/// <summary> /// 使用Post方法上传文件 /// </summary> /// <param name="url"></param> /// <param name="fileDictionary">需要上传的文件,Key:对应要上传的Name,Value:本地文件名</param> /// <returns></returns> public static string Upload(string url, Dictionary<string, string> fileDictionary, Encoding encoding = null) { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); request.Method = "POST"; Stream postStream = new MemoryStream(); #region 处理Form表单文件上传 var formUploadFile = fileDictionary != null && fileDictionary.Count > 0;//是否用Form上传文件 if (formUploadFile) { //通过表单上传文件 string boundary = "----" + DateTime.Now.Ticks.ToString("x"); string formdataTemplate = " --" + boundary + " Content-Disposition: form-data; name="{0}"; filename="{1}" Content-Type: application/octet-stream "; foreach (var file in fileDictionary) { try { var fileName = file.Value; //准备文件流 using (var fileStream = FileHelper.GetFileStream(fileName)) { var formdata = string.Format(formdataTemplate, file.Key, fileName /*Path.GetFileName(fileName)*/); var formdataBytes = Encoding.ASCII.GetBytes(postStream.Length == 0 ? formdata.Substring(2, formdata.Length - 2) : formdata);//第一行不需要换行 postStream.Write(formdataBytes, 0, formdataBytes.Length); //写入文件 byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { postStream.Write(buffer, 0, bytesRead); } } } catch (Exception ex) { throw ex; } } //结尾 var footer = Encoding.ASCII.GetBytes(" --" + boundary + "-- "); postStream.Write(footer, 0, footer.Length); request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary); } #endregion request.ContentLength = postStream != null ? postStream.Length : 0; request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8"; request.KeepAlive = true; request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36"; #region 输入二进制流 if (postStream != null) { postStream.Position = 0; //直接写入流 Stream requestStream = request.GetRequestStream(); byte[] buffer = new byte[1024]; int bytesRead = 0; while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } postStream.Close();//关闭文件访问 } #endregion HttpWebResponse response = (HttpWebResponse)request.GetResponse(); using (Stream responseStream = response.GetResponseStream()) { using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.GetEncoding("utf-8"))) { string retString = myStreamReader.ReadToEnd(); return retString; } } }