C# HttpClient 4.5 multipart/form-data upload

前端 未结 10 845
逝去的感伤
逝去的感伤 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:03

    Here's a complete sample that worked for me. The boundary value in the request is added automatically by .NET.

    var url = "http://localhost/api/v1/yourendpointhere";
    var filePath = @"C:\path\to\image.jpg";
    
    HttpClient httpClient = new HttpClient();
    MultipartFormDataContent form = new MultipartFormDataContent();
    
    FileStream fs = File.OpenRead(filePath);
    var streamContent = new StreamContent(fs);
    
    var imageContent = new ByteArrayContent(streamContent.ReadAsByteArrayAsync().Result);
    imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
    
    form.Add(imageContent, "image", Path.GetFileName(filePath));
    var response = httpClient.PostAsync(url, form).Result;
    

提交回复
热议问题