How to submit a multipart/form-data HTTP POST request from C#

后端 未结 5 1473
予麋鹿
予麋鹿 2020-12-15 20:10

What is the easiest way to submit an HTTP POST request with a multipart/form-data content type from C#? There has to be a better way than building my own request.

T

5条回答
  •  被撕碎了的回忆
    2020-12-15 20:55

    I have not tried this myself, but there seems to be a built-in way in C# for this (although not a very known one apparently...):

    private static HttpClient _client = null;
    
    private static void UploadDocument()
    {
        // Add test file 
        var httpContent = new MultipartFormDataContent();
        var fileContent = new ByteArrayContent(File.ReadAllBytes(@"File.jpg"));
        fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
        {
            FileName = "File.jpg"
        };
    
        httpContent.Add(fileContent);
        string requestEndpoint = "api/Post";
    
        var response = _client.PostAsync(requestEndpoint, httpContent).Result;
    
        if (response.IsSuccessStatusCode)
        {
            // ...
        }
        else
        {
            // Check response.StatusCode, response.ReasonPhrase
        }
    }
    

    Try it out and let me know how it goes.

    Cheers!

提交回复
热议问题