關於.NET winform模擬HttpWebRequest POST上傳文件需要注意的幾個地方

*注意事項

        要設置分割線 ,其中分割線無論是否包含“--”,在組裝消息頭時都要加上“--”(兩個 “-”),結束時也要加上“--”(兩個 “-”)另外,

        建議在開發的時候可以使用Fiddler抓包工具來測試自己的請求信息,與成功的信息對比。

具體方法如下:

        /// <summary>
        /// 上傳文件時的設置
        /// </summary>
        private static void SetMessage(HttpWebRequest webRequest, string urlString,string uploadLocalPath) {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(urlString);
            webRequest.ContentType = "multipart/form-data";

            //參數分割線
            string boundary = "-----" + DateTime.Now.Ticks.ToString();
            webRequest.ContentType += "; boundary=" + boundary;//添加分割線,告訴服務器自定義分割線是什麼
            
            //設置POST消息頭
            StringBuilder startStrBuilder = new StringBuilder();
            startStrBuilder.AppendFormat("--{0}", boundary);//此處注意開頭要添加 -- ,無論分割線中是否包含 --
            startStrBuilder.Append("\r\n");
            startStrBuilder.Append("Content-Disposition: form-data; name=\"editorFiles\"; filename=\"");
            startStrBuilder.Append(Path.GetFileName(uploadLocalPath));
            startStrBuilder.Append("\"");
            startStrBuilder.Append("\r\n");
            startStrBuilder.Append("Content-Type: image/jpeg");
            startStrBuilder.Append("\r\n");
            startStrBuilder.Append("\r\n");
            string strPostHeader = startStrBuilder.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

            //POST消息尾
            StringBuilder endStrBuilder = new StringBuilder();
            endStrBuilder.Append("\r\n");
            endStrBuilder.AppendFormat("--{0}--", boundary); //此處開頭與尾註意要添加 -- ,無論分割線中是否包含 --
            endStrBuilder.Append("\r\n");
            byte[] boundaryBytes = Encoding.UTF8.GetBytes(endStrBuilder.ToString());


            using (FileStream fs = new FileStream(uploadLocalPath, FileMode.Open, FileAccess.Read)) {
                long length = postHeaderBytes.Length + fs.Length + boundaryBytes.Length;
                webRequest.ContentLength = length;
                using (Stream requestStream = webRequest.GetRequestStream()) {
                    //寫入消息頭
                    requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

                    //寫入文件內容
                    byte[] buffer = new byte[checked((uint)Math.Min(4096, (int)fs.Length))];
                    int bytesRead = 0;
                    while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) != 0) {
                        requestStream.Write(buffer, 0, bytesRead);
                    }

                    //寫入消息尾部
                    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                }
            }
        }
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章