SoFunction
Updated on 2025-03-07

C# HttpClient uploads files and attaches other parameters

1. Details of Fiddler packet capture parameters

Content-Type: multipart/form-data; boundary="8d9ade1fd906a6a"
Content-Length: 39356
 
--8d9ade1fd906a6a
Content-Type: application/x-jpg
Content-Disposition: form-data; name=file; filename=
 
...File binary stream
--8d9ade1fd906a6a
Content-Disposition: form-data; name=toes
 
123@
--8d9ade1fd906a6a
Content-Disposition: form-data; name=subject
 
Test send attachment
--8d9ade1fd906a6a
Content-Disposition: form-data; name=Body
 
testHttpClientSend files+Additional parameter request
--8d9ade1fd906a6a

2. Use MultipartFormDataContent to encapsulate files and other parameters

Content-Type is when uploading the filemultipart/form-data, and other additional parameters must be identifiedform-data

  • 2.1. Convert the file to ByteArrayContent
        private static ByteArrayContent CreateByteArrayContent(string key, string fileName, string fileContent,
            byte[] fileBytes)
        {
            var fileByteArrayContent = new ByteArrayContent(fileBytes);
             = new MediaTypeHeaderValue(fileContent);
             = new ContentDispositionHeaderValue("form-data")
            {
                Name = key, //Interface matching name                FileName = fileName //Attachment file name            };
            return fileByteArrayContent;
        }
  • 2.2. Convert other attachment parameters to ByteArrayContent
        private static List<ByteArrayContent> CreateParamsByteArrayContent(IDictionary<string, string> dic)
        {
            var list = new List<ByteArrayContent>();
            if (dic == null ||  == 0) return list;
            foreach (var (key, value) in dic)
            {
                var valueBytes = Encoding.(value);
                var byteArray = new ByteArrayContent(valueBytes);
                 = new ContentDispositionHeaderValue("form-data")
                {
                    Name = key
                };
                (byteArray);
            }
 
            return list;
        }
  • 2.3. Build MultipartFormDataContent
        private static MultipartFormDataContent CreateContent(byte[] bytes,IDictionary&lt;string,string&gt; addParams)
        {
            var strBoundary = ("x"); //Separator 
            var resultContent = new MultipartFormDataContent(strBoundary);
            //document            var fileByteContent = CreateByteArrayContent("file", "", "application/x-jpg", bytes);
            (fileByteContent);
            //Other additional parameters            var paramsByteContent = CreateParamsByteArrayContent(addParams);
            (el =&gt;
            {
                (el);
            });
            return resultContent;
        }

3. Send a request

        static async Task Main(string[] args)
        {
 
            var dic = new Dictionary&lt;string, string&gt;
            {
                {"toes", "111@"},
                {"subject", "Test send attachment"},
                {"Body", "Test HttpClient to send file + extra parameter request"},
            };
 
            var filePath = @"d:\image\";
            using (var fileStream = (filePath, ))
            {
                var bytes = new byte[];
                (bytes, 0, );
                using (var client = new HttpClient())
                {
                    var message = new HttpRequestMessage(, "https://xxx/email/SendEmailIncludeAttach");
                     = CreateContent(bytes, dic);
                    var responseMessage = await (message);
                    if ()
                    {
                        var resStr = await ();
                        (resStr);
                    }
                }
            }
 
            ();
 
        }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.