[c# MultipartUpload]



FormUpload 클래스

public static class FormUpload
    private static readonly Encoding encoding = Encoding.UTF8;
    public static HttpWebResponse MultipartFormDataPost(string postUrl, string userAgent, Dictionary<string, object> postParameters)
        string formDataBoundary = "-----------------------------28947758029299";
        string contentType = "multipart/form-data; boundary=" + formDataBoundary;
        byte[] formData = GetMultipartFormData(postParameters, formDataBoundary);
        return PostForm(postUrl, userAgent, contentType, formData);
    private static HttpWebResponse PostForm(string postUrl, string userAgent, string contentType, byte[] formData)
        HttpWebRequest request = WebRequest.Create(postUrl) as HttpWebRequest;
        if (request == null)
            throw new NullReferenceException("request is not a http request");
        // Set up the request properties
        request.Method = "POST";
        request.ContentType = contentType;
        request.UserAgent = userAgent;
        request.CookieContainer = new CookieContainer();
        request.ContentLength = formData.Length;  // We need to count how many bytes we're sending. 
        using (Stream requestStream = request.GetRequestStream())
            // Push it out there
            requestStream.Write(formData, 0, formData.Length);
        return request.GetResponse() as HttpWebResponse;
    private static byte[] GetMultipartFormData(Dictionary<string, object> postParameters, string boundary)
        Stream formDataStream = new System.IO.MemoryStream();
        foreach (var param in postParameters)
            if (param.Value is FileParameter)
                FileParameter fileToUpload = (FileParameter)param.Value;
                // Add just the first part of this param, since we will write the file data directly to the Stream
                string header = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"; filename=\"{2}\";\r\nContent-Type: {3}\r\n\r\n", 
                    fileToUpload.FileName ?? param.Key, 
                    fileToUpload.ContentType ?? "application/octet-stream");
                formDataStream.Write(encoding.GetBytes(header), 0, header.Length);
                // Write the file data directly to the Stream, rather than serializing it to a string.
                formDataStream.Write(fileToUpload.File, 0, fileToUpload.File.Length);
                // Thanks to feedback from commenters, add a CRLF to allow multiple files to be uploaded
                formDataStream.Write(encoding.GetBytes("\r\n"), 0, 2);
                string postData = string.Format("--{0}\r\nContent-Disposition: form-data; name=\"{1}\"\r\n\r\n{2}\r\n", 
                formDataStream.Write(encoding.GetBytes(postData), 0, postData.Length);
        // Add the end of the request
        string footer = "\r\n--" + boundary + "--\r\n";
        formDataStream.Write(encoding.GetBytes(footer), 0, footer.Length);
        // Dump the Stream into a byte[]
        formDataStream.Position = 0;
        byte[] formData = new byte[formDataStream.Length];
        formDataStream.Read(formData, 0, formData.Length);
        return formData;
    public class FileParameter
        public byte[] File { get; set; }
        public string FileName { get; set; }
        public string ContentType { get; set; }
        public FileParameter(byte[] file) : this(file, null) { }
        public FileParameter(byte[] file, string filename) : this(file, filename, null) { }
        public FileParameter(byte[] file, string filename, string contenttype) 
            File = file;
            FileName = filename;
            ContentType = contenttype;


 // Read file data
FileStream fs = new FileStream("c:\\people.doc", FileMode.Open, FileAccess.Read);
byte[] data = new byte[fs.Length];
fs.Read(data, 0, data.Length);
// Generate post objects
Dictionary<string, object> postParameters = new Dictionary<string, object>();
postParameters.Add("filename", "People.doc");
postParameters.Add("fileformat", "doc");
postParameters.Add("file", new FormUpload.FileParameter(data, "People.doc", "application/msword"));
// Create request and receive response
string postURL = "http://localhost";
string userAgent = "Someone";
HttpWebResponse webResponse = FormUpload.MultipartFormDataPost(postURL, userAgent, postParameters);
// Process response
StreamReader responseReader = new StreamReader(webResponse.GetResponseStream());
string fullResponse = responseReader.ReadToEnd();

'C#' 카테고리의 다른 글

[LINQ to SQL]  (111) 2012.02.02
[IPv4] IPv4 주소 쉽게 알아내기  (88) 2012.02.01
[c# MultipartUpload]  (107) 2012.01.30
[CustomEvent] 간단한 이벤트 클래스 작성  (128) 2012.01.03
[WCF] WCF의 기초 통신  (177) 2011.12.19
[ASP.NET] ASP.NET - IIS 셋팅하면서 부닥치는 에러와 해결방법  (93) 2011.11.29
Yamecoder 야매코더_
C# 2012. 1. 30. 11:05

댓글을 달아 주세요

  1. 이전 댓글 더보기
  2. BlogIcon 600型楼承板机 2015.01.05 15:25  수정/삭제  댓글쓰기

    이용약관위배로 관리자 삭제된 댓글입니다.

  3. BlogIcon montblanc pen 2015.01.05 21:58  수정/삭제  댓글쓰기

    이용약관위배로 관리자 삭제된 댓글입니다.

  4. 匿名 2015.01.07 17:46  수정/삭제  댓글쓰기

    이용약관위배로 관리자 삭제된 댓글입니다.

  5. BlogIcon furla online 2015.01.18 00:22  수정/삭제  댓글쓰기

    이용약관위배로 관리자 삭제된 댓글입니다.

  6. BlogIcon furla bags on sale 2015.02.04 13:34  수정/삭제  댓글쓰기

    야에Inflation raises to be able to 17

    Inflation blossom with a 17 thirty days filled with '04 driven via growing foods costs in addition to Price range obligation outside outdoor hikes, acknowledged amounts have subjected.

    The client discount louis vuitton handbags Expenses List (CPI) hit 3. 7% last thirty days, the best simply because Nov '08 in addition to properly while watching 3. 5% expecte어간

  7. BlogIcon mont blanc pen 2015.02.06 02:38  수정/삭제  댓글쓰기

    려알The particular Big Industry Regarding Big Kid's Clothes

    Child years being obese is really growing, without any the foremost is getting excited about the particular potential prospects regarding influenced children. Nevertheless the community well being uncertainty may display an opportunity regarding retailers: Additionally sizing kids clothing is probably the nearly all ensuring marketplace ar스전

  8. BlogIcon burberry trench coat 2015.02.18 23:10  수정/삭제  댓글쓰기

    가메Pekovic forces Baby wolves more than Philly 94

    Philadelphia 76ers' Lavoy Allen, correct, breaks or cracks upward the rating try through Mn Timberwolves' Nikola Pekovic, associated with Montenegro, within the very first one fourth of the NBA golf ball online game Thursday, February. These people rapidly discovered which tough as well as drop is simply exactly how Nikola Pekovic wants this. Pekov그알

  9. BlogIcon furla bags online 2015.03.10 02:59  수정/삭제  댓글쓰기

    그던Nine Essential Travel Products for Spring,furla online shopping

    Spring is the perfect time to go hiking after a long winter spent indoors. But packing for a hiking trip can be very challenging, especially if you flying to your destination. You can either treat your hiking backpack as your suitcase, or you can pack a separate suitcase and somehow fit your backpack in it not great options. Outdoo수에

  10. BlogIcon oakley sunglassses outlet 2015.03.18 21:30  수정/삭제  댓글쓰기

    예는How to approach Unpleasant Employee Difficulties

    The same as everyone, everyone functions in different ways and contains an additional point of view on living. A person life-style, actions in addition to respect meter might effect their very own efficiency as well as the efficiency in addition to way of life in the extra staff as well. Together with just a great aside odor as well as disheveled고뉴

  11. BlogIcon cheap oakley sunglasses 2015.03.18 21:58  수정/삭제  댓글쓰기

    마알Things to view TELEVISION

    Caption "Ghost Predators Halloween night Live" Syfy

    Give,ray ban sunglasses, Jerr and also the TAPS team tend to be back again with regard to an additional reside analysis, getting queries through enthusiasts as well as using a weird period in the Pennhurst Condition College, a good forgotten asylum (! ) within Springtime Town, Pennsylvania. Positive thing, since i 일히

  12. BlogIcon tory burch wallet 2015.03.24 02:41  수정/삭제  댓글쓰기

    우습Cyclone view within These types of associated with Bengal proceeds,burberry handbags

    The actual develop is comparable to which associated with Extremely Cyclone Phailin which strike exactly the same coastline this past year as well as monitored exactly the same path following getting used delivery within the exact same area.

    However the surprise isn't prone to develop in order to just as muc스메

  13. BlogIcon burberry femme 2015.03.27 21:10  수정/삭제  댓글쓰기

    리그l'empereur n'aime pas le renforcement de peeresses. Jiang Qing. il y a trois pouces. a commenc&eacute; &agrave; l'action de l'agriculture. de sorte que, je suis tr&egrave;s heureux qu'il est mort. comme des gangs et du banditisme de l'arm&eacute;e dans le sud de la ville de centre (tels que la "mafia" et "fr&egrave;re") est rapidement de la consommation,Cette histoire illustre t shirt burberry pas로있

  14. BlogIcon furla handbags 2015.03.29 14:59  수정/삭제  댓글쓰기

    가일Adam Levine's New Clothing Line to Launch at Kmart and Shop Your Way in 2013

    If you ever wanted your boyfriend to look more like Adam Levine, the time has finally come. Sure, you can rip up a white T shirt or buy a leather jacket, but nothing is as authentic as the man personal designs.

    Though he won be collaborating with American Idol Nicki Minaj, mont blanc fountain pens both musicians tur지는

  15. BlogIcon femme burberry soldes 2015.03.30 11:27  수정/삭제  댓글쓰기

    마는24 ans aujourd'hui, tard dans la nuit, et le matin en alternance.|

    | Long Sheng monsieur de 65 ans &agrave; cause d'une h&eacute;morragie c&eacute;r&eacute;brale, de ne pas rester &agrave; la maison &agrave; Washington, dans l'ouest de la grue.|

    | quotidiennement dans la n&eacute;crologie de l'&eacute;valuation de son message quelques jours plus tard: "les &Eacute;tats - Unis depuis de마메

  16. BlogIcon mont blanc outlet 2015.04.04 19:55  수정/삭제  댓글쓰기

    있을Longboat Key police to photograph vehicle license plates

    Longboat Key, Florida Longboat Key has plenty of picture perfect oakley sunglasses spots, but later this month, town cameras will be pointed not at the louis vuitton luggage palms, but at the pavement.

    Cameras mounted near the two bridges leading to Longboat Key will take pictures of the vehicles both coming and going. The cameras wi습되

  17. BlogIcon burberry trench coat 2015.04.04 21:31  수정/삭제  댓글쓰기

    어메Increasing your own developing period

    Numerous areas may quickly end up being going through ice as well as very cold temps, which could jeopardize the actual success of the comfortable period veggie vegetation. Through maintaining ice from the simply leaves or even maintaining the actual heat round the vegetation a couple of levels hotter, chilly delicate vegetation might endure as well as carr가마

  18. 匿名 2015.04.08 09:20  수정/삭제  댓글쓰기

    단는and even better news is that their greatest extent EVER!Beautiful flowers and fittings add a touch of tartan jackets that unmistakable feminine essence, while injections of red.

    Purple and orange make this the biggest ever range of colors.Barbour waxed jackets, Barbour International Quilt Jacket, Jackets Barbour Polar Quilt .

    With the long and sunny summer break here, parents and kids 를를

  19. BlogIcon discount oakley sunglasses 2015.04.13 01:23  수정/삭제  댓글쓰기

    에부Pianist Zacharias from Kimmel

    Intermission chat from Wednesday's Religious Zacharias recital required upon threatening shades whenever 1 sage pianophile noticed, "He has a tendency to consider items to the actual severe. inch As well as why is Zacharias probably the most intriguing folk statesman computer keyboard personas is actually that you simply in no way understand that severe he will con이리

  20. BlogIcon furla handbags outlet 2015.04.13 04:16  수정/삭제  댓글쓰기

    리마3 homes destroyed inside house fire place inside Lewis Areas

    fire place merely kept disbursing, mentioned Gleaming Germsheid, which existence merely two entrances reduce in your home that in the beginning taken fire place. happened genuinely, genuinely fast. related to area people gathered outside in addition to seen helplessly because the homes travelled upwards inside fireplace.

    smoke ciga마리

  21. BlogIcon oakley sunglasses 2015.04.14 01:53  수정/삭제  댓글쓰기

    뉴지Fundamental Income For each Reveal Fundamental EPS versus

    Whenever you evaluate a business, you need to do this upon 2 amounts, the organization and also the reveal Should you choose ABC, Inc. may be worth $5 million in general, a person will be able to split this lower simply by separating the actual $5 million cost through the amount of gives exceptional. Regrettably, this isn usually that ea는뉴

Powerd by Tistory, designed by criuce