【.net/.net core】使用form-data方式发起post请求

 使用场景:一般为在发起请求时,需要带着文件对象,即File类型参数。

public async void  PostByFormData() {
            //创建一个MultipartFormDataContent对象,构建multipart/form-data请求体
            MultipartFormDataContent pushMemberParams = new MultipartFormDataContent();
            string fileUrl= "https://localhost:8081/image/123.png";//模拟网络图片/文件

            // 使用HttpClient获取图片/文件数据
            byte[] fileBtyes = await DownloadImageBytes(fileUrl);

            // 创建HttpClient实例
            HttpClient client = new HttpClient();
            // 添加文件内容到multipart/form-data内容中
            pushMemberParams.Add(new StreamContent(new MemoryStream(fileBtyes )), "fileKey", "123.png");//此处需注意,文件需要添加为流内容,需要先将字节数组转换为流类型,然后添加
            pushMemberParams.Add(new StringContent("张三"), "Name");
            var response = await client.PostAsync("https://localhost:8082/saveFile", pushMemberParams);//https://localhost:8082/saveFil为处理请求接口地址
            // 确保响应成功
            response.EnsureSuccessStatusCode();
            // 读取响应内容
            var responseBody = await response.Content.ReadAsStringAsync();
            //需要返回内容可在此处添加,对应需要修改方法的返回类型
        }

将文件流转换为字节数组方法

/// 
        /// 将文件流转换为字节数组
        /// 
        /// 
        /// 
        public byte[] ConvertFileStreamToByteArray(string filePath)
        {
            // 创建一个FileStream对象来读取文件
            using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
            {
                // 获取文件的大小
                int length = (int)fileStream.Length;
                byte[] byteArray = new byte[length];

                // 从文件流中读取数据到字节数组中
                fileStream.Read(byteArray, 0, length);
                return byteArray;
            }
        }

将网络图片地址转换为字节数组方法

/// 
        /// 下载图片
        /// 
        /// 
        /// 
        static async Task DownloadImageBytes(string imageUrl)
        {
            using (HttpClient client = new HttpClient())
            {
                // 发起GET请求
                HttpResponseMessage response = await client.GetAsync(imageUrl);
                response.EnsureSuccessStatusCode(); // 检查响应状态码是否成功
                byte[] imageBytes = await response.Content.ReadAsByteArrayAsync(); // 读取内容为字节数组
                return imageBytes;
            }
        }

你可能感兴趣的:(.net,.netcore)