본문 바로가기
C# /WindowsForm

[C#] HttpWebRequest를 이용한 Multipart/form-data 파일 업로드 예제

by Hwoarang757 2020. 11. 16.

Header 부분의 Content-Disposition: form-data ;name="ID" ;filename="파일명" ;  Content-Type이 octet-stream 으로 설정되어야 파일이 정상적으로 업로드 처리 되었습니다. 테스트 시에 [multipart/form-data] 로 설정시에 WAS에 파일이 업로드 된 후 응답이 없이 timeout 이 발생하는 현상이 자주 발생 하였습니다..


        public object lockObj = new object();
        public static string FileUploadRequestPost(string url,string filePath,Dictionary<String,String> parameters, ref CookieContainer cookie)
        {
            lock (lockObj)
            {
                string resdata;
                try
                {
                    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
                    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
                    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";

                    byte[] boundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
                    byte[] endboundarybytes = Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                    byte[] buffer = new byte[4096];

                    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                    request.ServicePoint.Expect100Continue = false;
                    request.Method = "POST";
                    request.CookieContainer = cookie;
                    request.ContentType = "multipart/form-data; boundary=" + boundary;

                    using (Stream requestStream = request.GetRequestStream())
                    {

                        foreach (KeyValuePair<String, String> param in parameters)
                        {
                            requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                            string formItem = string.Format(formdataTemplate, param.Key, param.Value);
                            byte[] formItemByte = System.Text.Encoding.UTF8.GetBytes(formItem);
                            requestStream.Write(formItemByte, 0, formItemByte.Length);
                        }

                        requestStream.Write(boundarybytes, 0, boundarybytes.Length);
                        //octet-stream 으로 변경 처리 진행 
                        //string header = string.Format(headerTemplate, "outfaxfile", Path.GetFileName(filePath), "multipart/form-data");
                        string header = string.Format(headerTemplate, "outfaxfile", Path.GetFileName(filePath), "octet-stream");
                        byte[] headerByte = System.Text.Encoding.UTF8.GetBytes(header);
                        requestStream.Write(headerByte, 0, headerByte.Length);

                        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(endboundarybytes, 0, endboundarybytes.Length);

                        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                        {
                            using(StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8, true)) 
                             resdata = sr.ReadToEnd();
                        }

                    }
                }
                catch (Exception exception) {
                   
                }
                finally {

                }
                return resdata;
            }
        }