C# Post发送包含文件和字符串的FormData

首次发布:2023-06-29 14:26
public void PostFormData()
{
    string url = "http://localhost:5000/upload";
    using (HttpClient client = new HttpClient())
    {
        using (MultipartFormDataContent formData = new MultipartFormDataContent())
        {
            // 添加字符串参数
            string stringValue = "Hello, World!";
            formData.Add(new StringContent(stringValue), "stringParam");

            // 添加文件参数
            string filePath = @"C:\path\to\file";
            using (FileStream fileStream = File.Open(filePath, FileMode.Open))
            {
                formData.Add(new StreamContent(fileStream), "FileParam", Path.GetFileName(filePath));
                // 发送请求
                HttpResponseMessage response = client.PostAsync(url, formData).Result;

                // 处理响应
                if (response.IsSuccessStatusCode)
                {
                    string responseContent = response.Content.ReadAsStringAsync().Result;
                    Console.WriteLine("Upload successful. Response: " + responseContent);
                }
                else
                {
                    Console.WriteLine("Upload failed. Status code: " + response.StatusCode);
                }
            }
        }
    }
}

本文来自 www.luofenming.com