C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 1083
逝去的感伤
逝去的感伤 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 05:49

    It works more or less like this (example using an image/jpg file):

    async public Task UploadImage(string url, byte[] ImageData)
    {
        var requestContent = new MultipartFormDataContent(); 
        //    here you can specify boundary if you need---^
        var imageContent = new ByteArrayContent(ImageData);
        imageContent.Headers.ContentType = 
            MediaTypeHeaderValue.Parse("image/jpeg");
    
        requestContent.Add(imageContent, "image", "image.jpg");
    
        return await client.PostAsync(url, requestContent);
    }
    

    (You can requestContent.Add() whatever you want, take a look at the HttpContent descendant to see available types to pass in)

    When completed, you'll find the response content inside HttpResponseMessage.Content that you can consume with HttpContent.ReadAs*Async.

提交回复
热议问题