C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 1079
逝去的感伤
逝去的感伤 2020-11-22 05:39

Does anyone know how to use the HttpClient in .Net 4.5 with multipart/form-data upload?

I couldn\'t find any examples on the internet.

10条回答
  •  长发绾君心
    2020-11-22 06:12

    I'm adding a code snippet which shows on how to post a file to an API which has been exposed over DELETE http verb. This is not a common case to upload a file with DELETE http verb but it is allowed. I've assumed Windows NTLM authentication for authorizing the call.

    The problem that one might face is that all the overloads of HttpClient.DeleteAsync method have no parameters for HttpContent the way we get it in PostAsync method

    var requestUri = new Uri("http://UrlOfTheApi");
    using (var streamToPost = new MemoryStream("C:\temp.txt"))
    using (var fileStreamContent = new StreamContent(streamToPost))
    using (var httpClientHandler = new HttpClientHandler() { UseDefaultCredentials = true })
    using (var httpClient = new HttpClient(httpClientHandler, true))
    using (var requestMessage = new HttpRequestMessage(HttpMethod.Delete, requestUri))
    using (var formDataContent = new MultipartFormDataContent())
    {
        formDataContent.Add(fileStreamContent, "myFile", "temp.txt");
        requestMessage.Content = formDataContent;
        var response = httpClient.SendAsync(requestMessage).GetAwaiter().GetResult();
    
        if (response.IsSuccessStatusCode)
        {
            // File upload was successfull
        }
        else
        {
            var erroResult = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            throw new Exception("Error on the server : " + erroResult);
        }
    }
    

    You need below namespaces at the top of your C# file:

    using System;
    using System.Net;
    using System.IO;
    using System.Net.Http;
    

    P.S. Sorry about so many using blocks(IDisposable pattern) in my code. Unfortunately, the syntax of using construct of C# doesn't support initializing multiple variables in single statement.

提交回复
热议问题