개발/C#.net / / 2023. 5. 13. 19:44

[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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
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<stringobject> parameters)
    {
 
        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);
        request.ContentType = "multipart/form-data; boundary=" + boundary;
        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<stringobject> pair in parameters)
                {
 
                    requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                    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)
                        {
                            // upload from file
                            using (FileStream fileStream = File.OpenRead(file.FilePath))
                            {
                                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                                    requestStream.Write(buffer, 0, bytesRead);
                                fileStream.Close();
                            }
                        }
                        else
                        {
                            // upload from given stream
                            while ((bytesRead = file.Stream.Read(buffer, 0, buffer.Length)) != 0)
                                requestStream.Write(buffer, 0, bytesRead);
                        }
                    }
                    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();
        }
 
 
    }
}
cs
 

호출 시 예제

설정된 변수 값은 예제여서 임의로 작성

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
string result = string.Empty; // 전송 후 결과값
result = RequestHelper.PostMultipart(
                             "http://www.naver.com"new Dictionary<stringobject>() 
                            {
                                { 
                                    "uploadFile0"new FormFile() 
                                    { 
                                    Name = string.Format("{0}_{1}_0",blbd_no, pstg_no), -- 보내지는 파일명 
                                    ContentType = "application/pdf",  -- 파일 타입
                                    FilePath = LocalFullPath  -- 로컬파일경로
                                    } 
                                }
                            }
                        );                   
cs

 

'개발 > C#.net' 카테고리의 다른 글

[C#] GET, POST 전송 및 처리(HttpWebRequest)  (0) 2019.01.17
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유