C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# HttpClient上传文件并附带其它参数

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

作者:csdmwinter

这篇文章主要介绍了C# HttpClient上传文件并附带其它参数方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教

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

        private static ByteArrayContent CreateByteArrayContent(string key, string fileName, string fileContent,
            byte[] fileBytes)
        {
            var fileByteArrayContent = new ByteArrayContent(fileBytes);
            fileByteArrayContent.Headers.ContentType = new MediaTypeHeaderValue(fileContent);
            fileByteArrayContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = key, //接口匹配name
                FileName = fileName //附件文件名
            };
            return fileByteArrayContent;
        }
        private static List<ByteArrayContent> CreateParamsByteArrayContent(IDictionary<string, string> dic)
        {
            var list = new List<ByteArrayContent>();
            if (dic == null || 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;
        }
        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);
            //其它附加参数
            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 message = 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();
 
        }

总结

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文