.Net使用HttpClient以multipart/form-data形式post上传文件及其相关参数

httpClient模仿Postman的form-data格式

 api接口

 [HttpPost(Name = "/Test/FileTest")]
        public JGResponse<PutFileByNameResponse> FileTest([FromForm]PutFileByNameRequest requestDto)
        {
            var capthch = GetCaptcha();
            var token = GetToken(capthch.Data);

            requestDto.jptlAuth = token.Data.access_token;
            var result = RegulatoryPlatformSDK.PutFileByName(requestDto);
            return result;
        }

接口对象

public class JGRequestDto
    {
        /// <summary>
        /// 验证码
        /// </summary>
        [Required]
        [Description("jptl-auth")]
        public string jptlAuth { get; set; }
    }

public class PutFileByNameRequest : JGRequestDto
    {
        /// <summary>
        /// 文件
        /// </summary>
        public IFormFile file { get; set; }

        /// <summary>
        /// 文件名
        /// </summary>
        public string fileName { get; set; }
    }

第三方接口请求

public string Upload(UploadRequestDto dto)
        {
            if (dto == null)
                return "";

            //请求
            var url = SDKConfig.Host + "/third-service/upload";
            List<ByteArrayContent> list = new List<ByteArrayContent>();

            var interfaceCode = new ByteArrayContent(Encoding.UTF8.GetBytes(dto.interfaceCode));
            interfaceCode.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "interfaceCode" };
            list.Add(interfaceCode);

            var param = new ByteArrayContent(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(dto.param)));
            param.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "param" };
            list.Add(param);

            var file = new ByteArrayContent(ReadFileBytes(dto.file));
            file.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data") { Name = "file", FileName = dto.param["fileName"].ToString() };
            list.Add(file);

            var content = new MultipartFormDataContent();
            Action<List<ByteArrayContent>> act = (dataContents) =>
            {
                foreach (var byteArrayContent in dataContents)
                {
                    content.Add(byteArrayContent);
                }
            };
            act(list);

            var response = RequestHelper.HttpPostToFormData(url, content);  //, "application/x-www-form-urlencoded"
            var responseJson = new ResponseDto<JGResponse<PutFileByNameResponse>>();
            try
            {
                responseJson = JsonConvert.DeserializeObject<ResponseDto<JGResponse<PutFileByNameResponse>>>(response);
            }
            catch (Exception)
            {
                var json = JsonConvert.DeserializeObject<ResponseDto<string>>(response);
                return json.Data;
            }
            if (responseJson == null)
                return "";
            return JsonConvert.SerializeObject(responseJson.Data);
        }
private static Byte[] ReadFileBytes(IFormFile fileData)
        {
            byte[] data;
            using (var ms=new MemoryStream())
            {
                fileData.CopyTo(ms);
                data = ms.ToArray();
            }

            return data;
        }

post请求

 /// <summary>
        /// 发起POST异步请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public static string HttpPostToFormData(string url, MultipartFormDataContent formData)
        {
            string result = null;
            try
            {
                HttpClient httpClient = new HttpClient();
                HttpResponseMessage response = httpClient.PostAsync(url, formData).Result;
                if (response.IsSuccessStatusCode)
                {
                    result = response.Content.ReadAsStringAsync().Result;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return result;
        }

 

posted @ 2023-05-23 17:29  潇潇mini  阅读(807)  评论(0编辑  收藏  举报