有時候,咱們須要在後臺端發起向指定的「文件接收接口」的文件傳輸請求,能夠採用HttpWebRequest方式實現文件傳輸請求。cookie
一、HttpWebRequest文件傳輸請求的代碼以下:post
其中,url爲外部的文件接收接口,url中能夠跟多個參數,如: http:project/Weixin/SaveUploadFile?path={0}ui
filePath爲待上傳文件的物理路徑url
/// <summary> /// 傳輸文件到指定接口 /// </summary> /// <param name="url"></param> /// <param name="filePath">文件物理路徑</param> /// <returns></returns> public static string PostFile(string url, string filePath) { // 初始化HttpWebRequest HttpWebRequest httpRequest = (HttpWebRequest)HttpWebRequest.Create(url); // 封裝Cookie Uri uri = new Uri(url); Cookie cookie = new Cookie("Name", DateTime.Now.Ticks.ToString()); CookieContainer cookies = new CookieContainer(); cookies.Add(uri, cookie); httpRequest.CookieContainer = cookies; if (!File.Exists(filePath)) { return "文件不存在"; } FileInfo file = new FileInfo(filePath); // 生成時間戳 string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); byte[] boundaryBytes = Encoding.ASCII.GetBytes(string.Format("\r\n--{0}--\r\n", strBoundary)); // 填報文類型 httpRequest.Method = "Post"; httpRequest.Timeout = 1000 * 120; httpRequest.ContentType = "multipart/form-data; boundary=" + strBoundary; // 封裝HTTP報文頭的流 StringBuilder sb = new StringBuilder(); sb.Append("--"); sb.Append(strBoundary); sb.Append(Environment.NewLine); sb.Append("Content-Disposition: form-data; name=\""); sb.Append("file"); sb.Append("\"; filename=\""); sb.Append(file.Name); sb.Append("\""); sb.Append(Environment.NewLine); sb.Append("Content-Type: "); sb.Append("multipart/form-data;"); sb.Append(Environment.NewLine); sb.Append(Environment.NewLine); byte[] postHeaderBytes = Encoding.UTF8.GetBytes(sb.ToString()); // 計算報文長度 long length = postHeaderBytes.Length + file.Length + boundaryBytes.Length; httpRequest.ContentLength = length; // 將報文頭寫入流 Stream requestStream = httpRequest.GetRequestStream(); requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
//文件流循環寫入 byte[] buffer = new byte[4096]; int bytesRead = 0; using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read)) { while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0) { requestStream.Write(buffer, 0, bytesRead); } } // 將報文尾部寫入流 requestStream.Write(boundaryBytes, 0, boundaryBytes.Length); // 關閉流 requestStream.Close(); using (HttpWebResponse myResponse = (HttpWebResponse)httpRequest.GetResponse()) { StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8); var rs = sr.ReadToEnd(); return rs; //Console.WriteLine("反饋結果" + responseString); } }
二、文件接收端:url接口代碼以下spa
其中,JsonResultData類爲自身項目中的一個傳輸類;code
Base.Config.BConfig.GetConfigToString(path) 爲自身項目中在配置文件中根據鍵得到值的方法。orm
/// <summary> /// 保存平臺端傳來的文件 /// </summary> /// <param name="path"></param> /// <param name="file"></param> /// <returns></returns> public ActionResult SaveUploadFile(string path, HttpPostedFileBase file) { JsonResultData result = new JsonResultData(); try { string myPath = Base.Config.BConfig.GetConfigToString(path);//配置文件中讀取路徑 if (string.IsNullOrWhiteSpace(myPath)) { throw new Exception("未配置附件存放路徑,請聯繫管理員配置"+path); } if (Directory.Exists(myPath) == false) { Directory.CreateDirectory(myPath); } file.SaveAs(myPath + "\\" + file.FileName); result.IsSuccess = true; result.Message = "文件保存成功!"+path; } catch (Exception ex) { result.IsSuccess = false; result.Message = ex.Message; BLog.Write(BLog.LogLevel.WARN, "上傳附件出錯:" + ex.ToString()); } return Json(result, JsonRequestBehavior.AllowGet); }