开发者

C# HttpClient上传文件并附带其它参数方式

目录
  • 1、Fiddler抓包参数详情
  • 2、使用MultipartFormDataContent封装文件和其它参数
  • 3、发送请求
  • 总结

1、Fiddler抓包参数详情

Content-Type: multipart/form-data; boundary="8d9ade1fd906a6a"
Content-Length: 39356
 
--8d9ade1fd906a6a
Content-Type: application/x-jpg
Content-Disposition: form-data; name=file; filename=test.jpg
 
...文件二进制流
--8d9ade1fd906a6a
Content-Disposition: form-data; name=toes
 
123@qq.com
--8d9ade1fd906a6a
Content-Disposition: form-data; name=subject
 
测试发送附件
--8d9ade1fd906a6a
Content-Disposition: form-data; name=Body
 
测试HttpClient发送文件+额外参数请求
--8d9ade1fd906a6a

2、使用MultipartFormDataContent封装文件和其它参数

上传文件时Content-Type是multipart/form-data,并且其它额外参数都要标识form-data

  • 2.1、把文件转成ByteArrayContent
        private static ByteArrayContent CreateByteArrayContent(string key, string fileName, string fileContent,
            byte[] fileBytes)
        {
            var fileByteArrayContent = new ByteArrayContent(fileBytes);
            fileByteArrayContent.Headers.ContentType = new MediaTypeHeaderValue(fileContent);
            fileByteArrayContent.http://www.devze.comHeaders.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = key, //接口匹配name
                FileName = fileName //附件文件名
            };
            return fileByteArrayContent;
        }
  • 2.2、把其它附件参数转成ByteArrayContent
        private static List<ByteArrayContent> CreateParamsByteArrayContent(IDictionary<string, string> dic)
        {
            var list = new List<ByteArrayContent>();
            if (dic == nuwww.devze.comll || dic.Count == 0) return list;
            foreach (var (key, value) in dic)
            {
                var valueBytes = Encoding.UTF8.GetBytes(value);
                var byteArray = new ByteArrayContent(valueBytes);
                byteArray.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
                {
                    Name = key
                };
                list.Add(byteArray);
            }
 
            return list;
        }
  • 2.3、构建MultipartFormDataContent
        private static MultipartFormDataContent CreateContent(byte[] bytes,IDictionary<string,string> addParams)
        {
            var strBoundary = DateTime.Now.Ticks.ToString("x"); //分隔符
 
            var resultContent = new MultipartFormDataContent(strBoundary);
            //文件
            var fileByteContent = CreateByteArrayContent("file", "test.jpg", "application/x-jpg", bytes);
            resultContent.Add(fileByteContent);
 javascript           //其它附加参数
            var paramsByteContent = CreateParamsByteArrayContent(addParams);
            paramsByteContent.ForEach(el =>
            {
                resultContent.Add(el);
            });
            return resultContent;
        }

3、发送请求

        static async Task Main(string[] args)
        {
 
            var dic = new Dictionary<string, string>
            {
                {"toes", "111@qq.com"},
                {"subject", "测试发送附件"},
                {"Body", "测试HttpClient发送文件+额外参数请求"},
       编程客栈     };
 
            var filePath = @"d:\image\shui.jpg";
            using (var fileStream = File.Open(filePath, FileMode.Open))
            {
                var bytes = new byte[fileStream.Length];
                fileStream.Read(bytes, 0, bytes.Length);
                using (var client = new HttpClient())
                {
                    var messageandroid = new HttpRequestMessage(HttpMethod.Post, "https://xxx/email/SendEmailIncludeAttach");
                    message.Content = CreateContent(bytes, dic);
                    var responseMessage = await client.SendAsync(message);
                    if (responseMessage.IsSuccessStatusCode)
                    {
                        var resStr = await responseMessage.Content.ReadAsStringAsync();
                        Console.WriteLine(resStr);
                    }
                }
            }
 
            Console.ReadKey();
 
        }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程客栈(www.devze.com)。

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新开发

开发排行榜