본문 바로가기
Unity3D/Unity & C#

Unity & C# ~ multipart 코드 분석

by 캬캬백곰 2022. 6. 28.
728x90

참고 블로그 : https://spirit32.tistory.com/21

 

[C#] multipart/form-data 파일 업로드

C# 에서 multipart/form-data로 파일 업로드하는 예제. 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51..

spirit32.tistory.com

 

//object형식으로 만들 클래스
//파일을 전송할 때 object형식으로 보내지 않으면 형식에러가 발생함
public class FormFile
{
    public string Name { get; set; } 
    public string ContentType { get; set; } 
    public string FilePath { get; set; } 
    public Stream Stream { get; set; }
}
 
public class RequestHelper
{ 
    public static string PostMultipart(string url, Dictionary<string, object> parameters)
    {
    	//바운더리 설정
        //content-type 헤더에 포함된 boundary 매개 변수 값을 설정
        string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
        byte[] boundaryBytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");
 
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
        
        //GetResponse() 및 GetRequestStream() 메서드의 제한 시간 값을 밀리초 단위로 설정
        request.Timeout = 10000;
        
        //MIME 프로토콜 설정
        //multipart 프로토콜로 설정
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        
        //HTTP Accept 헤더의 값 설정
        //기본값은 null
        request.Accept = "application/json";
        
        //인터넷 리소스에 접속하는 데 사용할 요청 메소드
        //HTTP1.1 프로토콜 동사(GET, HEAD, POST, PUT, DELETE, TRACE 또는 OPTIONS)로 설정
        //기본값은 GET
        request.Method = "POST";
        
        //인터넷 리소스에 영구 연결을 할 것인지 여부를 나타내는 값
        request.KeepAlive = true;
        
        //요청에 대한 인증 정보를 가져오거나 설정
        request.Credentials = System.Net.CredentialCache.DefaultCredentials;
 
        if (parameters != null && parameters.Count > 0)
        {
        	//스트림 초기화
            using (Stream requestStream = request.GetRequestStream())
            {
                foreach (KeyValuePair<string, object> pair in parameters)
                {
                	//바운드리 BYTE형식 쓰기
                    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    
                    //value값이 오브젝트 형식일 때
                    if (pair.Value is FormFile)
                    {
                        FormFile file = pair.Value as FormFile;
                        string header = "Content-Disposition: form-data; name=\"" + pair.Key + "\"; filename=\"" + file.Name + "\"\r\nContent-Type: " + file.ContentType + "\r\n\r\n";
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(header);
                        requestStream.Write(bytes, 0, bytes.Length);
                        byte[] buffer = new byte[32768];
                        int bytesRead;
                        if (file.Stream == null)
                        {
                            //파일 업로드
                            using (FileStream fileStream = File.OpenRead(file.FilePath))
                            {
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                    requestStream.Write(buffer, 0, bytesRead);
                                fileStream.Close();
                            }
                        }
                        else 
                        {
                            while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                                requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                    //value 값이 오브젝트 형식이 아닐 때
                    else
                    {
                        string data = "Content-Disposition: form-data; name=\"" + pair.Key + "\"\r\n\r\n" + pair.Value;
                        byte[] bytes = System.Text.Encoding.UTF8.GetBytes(data);
                        requestStream.Write(bytes, 0, bytes.Length);
                    }
                }
 
                byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
                requestStream.Write(trailer, 0, trailer.Length);
                requestStream.Close();
            }
        }
 
        using (WebResponse response = request.GetResponse())
        {
            using (Stream responseStream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(responseStream))
                return reader.ReadToEnd();
        }
    }
}

 

- 참고사항

1. boundary는 필수 사항

2. 400에러는 object 형식이 맞지 않아서 발생할 수 있음

3. 500에러는 서버가 요청을 받을 수 없을 때 발생

728x90
반응형