C# 에서 multipart/form-data로 파일 업로드하는 예제.

홈 > 공유팁! > 프로그램 관련
프로그램 관련

C# 에서 multipart/form-data로 파일 업로드하는 예제.

꽁스짱 0 1259

C# 에서 multipart/form-data로 파일 업로드하는 예제.

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();
        }
 
 
    }
}




호출 시 예제

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

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  -- 로컬파일경로
                                    } 
                                }
                            }
                        );     










0 Comments
제목