C# HttpClient 4.5 multipart/form-data upload

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

    Try this its working for me.

    private static async Task Upload(string actionUrl)
    {
        Image newImage = Image.FromFile(@"Absolute Path of image");
        ImageConverter _imageConverter = new ImageConverter();
        byte[] paramFileStream= (byte[])_imageConverter.ConvertTo(newImage, typeof(byte[]));
    
        var formContent = new MultipartFormDataContent
        {
            // Send form text values here
            {new StringContent("value1"),"key1"},
            {new StringContent("value2"),"key2" },
            // Send Image Here
            {new StreamContent(new MemoryStream(paramFileStream)),"imagekey","filename.jpg"}
        };
    
        var myHttpClient = new HttpClient();
        var response = await myHttpClient.PostAsync(actionUrl.ToString(), formContent);
        string stringContent = await response.Content.ReadAsStringAsync();
    
        return response;
    }
    
        

    提交回复
    热议问题