출처 : https://stackoverflow.com/questions/566462/upload-files-with-httpwebrequest-multipart-form-data





2015/08/21 - [프로그램 자료/ASP.NET] - [ASP.NET] WebAPI RESTful Service Client C# 웹API 레스트서비스 클라이언트 소스 POST GET 전송





private void btn_uploadtest_Click(object senderEventArgs e)
{
    string token = "eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbiIsImF1dGhzIjpbeyJhdXRob3JpdHkiOiJST0xFX1VTRVIifSx7ImF1dGhvcml0eSI6IlJPTEVfQURNSU4ifV0sImV4cCI6MTYwMzAxMzI0OSwiaWF0IjoxNjAyNDA4NDQ5fQ.FfUMOd8NIFlUBCE6aZ1zZvR_IHK6MKiCA6lGfqL3yCZRIGS02c7IY9oBWt824_RAPjSZjbsX3-T3MYIH5C6m1g";

    string msg;

    NameValueCollection nvc = new NameValueCollection();
    nvc.Add("contentId""1");
    HttpUploadFile("http://localhost:9999/admin/file"@"D:\util\mLauncher_bin.zip""file""application/octet-stream"tokennvcout msg);

    Console.WriteLine(msg);



}

public static bool HttpUploadFile(string urlstring filestring paramNamestring contentTypestring accessTokenNameValueCollection nvcout string Msg)
{
    bool _flag = false;
    Msg = null;

    string boundary = "---------------------------" + DateTime.Now.Ticks.ToString("x");
    byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n");

    HttpWebRequest wr = (HttpWebRequest)WebRequest.Create(url);
    wr.PreAuthenticate = true;
    wr.Headers.Add("Authorization""Bearer " + accessToken);
    wr.Accept = "application/json";

    wr.ContentType = "multipart/form-data; boundary=" + boundary;
    wr.Method = "POST";
    wr.KeepAlive = true;
    wr.Credentials = System.Net.CredentialCache.DefaultCredentials;

    Stream rs = wr.GetRequestStream();

    string formdataTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}";
    foreach (string key in nvc.Keys)
    {
        rs.Write(boundarybytes0boundarybytes.Length);
        string formitem = string.Format(formdataTemplatekeynvc[key]);
        byte[] formitembytes = System.Text.Encoding.UTF8.GetBytes(formitem);
        rs.Write(formitembytes0formitembytes.Length);
    }
    rs.Write(boundarybytes0boundarybytes.Length);

    string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
    string header = string.Format(headerTemplateparamNamePath.GetFileName(file), contentType);
    byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
    rs.Write(headerbytes0headerbytes.Length);

    FileStream fileStream = new FileStream(fileFileMode.OpenFileAccess.Read);
    byte[] buffer = new byte[4096];
    int bytesRead = 0;
    while ((bytesRead = fileStream.Read(buffer0buffer.Length)) != 0)
    {
        rs.Write(buffer0bytesRead);
    }
    fileStream.Close();

    byte[] trailer = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "--\r\n");
    rs.Write(trailer0trailer.Length);
    rs.Close();

    WebResponse wresp = null;
    try
    {
        using (HttpWebResponse resp = wr.GetResponse() as HttpWebResponse)
        {
            if (resp.StatusCode == HttpStatusCode.OK)
            {
                _flag = true;
            }
            StreamReader reader = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding("UTF-8"));
            Msg = reader.ReadToEnd();
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
        if (wresp != null)
        {
            wresp.Close();
            wresp = null;
        }
    }
    finally
    {
        wr = null;
    }


    return _flag;
}










Posted by motolies
,