C# HttpClient 서버에 파일 업로드(multipart/form-data)

1705 단어 C#
string reqUrl = JsonrpcHttpClient.MakeRpcUrl(typeof(Wfm_SimReport).Name, "save");

using (HttpClient client = new HttpClient(new HttpClientHandler() { UseCookies = false }))// Cookie UseCookies = false
{
                               
    string boundary = string.Format("----WebKitFormBoundary{0}",DateTime.Now.Ticks.ToString("x"));

    MultipartFormDataContent content = new MultipartFormDataContent(boundary);

    #region  

    content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    content.Headers.Add("Cookie", TokenManager.Token);
    content.Headers.Add("client", "true");

    #endregion

    if (string.IsNullOrEmpty(fullPath) && !File.Exists(fullPath))
    {
        return false;
    }

    string fileName = Path.GetFileName(fullPath);

    #region Stream 

    FileStream fStream = File.Open(fullPath, FileMode.Open, FileAccess.Read);

    content.Add(new StreamContent(fStream, (int)fStream.Length), "file", fileName);
                
    #endregion

    content.Add(new StringContent(JsonHelper.Serialize(entity)), "dtoStr");
              
    var result = client.PostAsync(reqUrl, content).Result;

    try
    {
        if (result.IsSuccessStatusCode)
        {
            string rslt = result.Content.ReadAsStringAsync().Result;

            Debug.WriteLine(rslt);

            return true;
        }
    }
    catch (Exception ex)
    {
        Debug.WriteLine(string.Format(" : :{0}, :{1}",ex.Message,ex.StackTrace));
    }
    finally
    {
        // 
        fStream.Close();
        client.Dispose();
    }                
 }

좋은 웹페이지 즐겨찾기