SoFunction
Updated on 2025-03-07

Multipart/form-data submit files and parameters in C#

C# multipart/form-data submit files and parameters

 public static string PostJsonData(string url, Dictionary<string, string> dic, string imgfile)
        {       
       string str = "";
            try
            {
                HttpClient client = new HttpClient();
                var postContent = new MultipartFormDataContent();
                string boundary = ("--{0}", ("x"));
                ("ContentType", $"multipart/form-data, boundary={boundary}");
               string image_file_Type="faceImage";
                (new ByteArrayContent((imgfile)), image_file_Type, imgfile);
                foreach (var key in )
                {
                    (new StringContent(dic[key].ToString()), key);
                }
                HttpResponseMessage response = (url, postContent).Result;
                str = ().Result;
                
            }
            catch (Exception ex)
            {
                ("PostJsonData:" + ());
            }
            return str;
  }

C# POST multipart/form-data case

using System;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
using ;
namespace 
{
    /// &lt;summary&gt;
    /// Korean picture reporting interface    /// &lt;/summary&gt;
    class HanGuoLogisticsPic : ISendPackageInfo
    {
        public bool CheckProcessHasRun()
        {
            throw new NotImplementedException();
        }
        UserConfigInfo config = ().userConfig;
        private static object _loc = new object();
        private Thread DSuPicUpload;
        public bool CheckTicketNumHasEffective(string ticketsNum)
        {
            throw new NotImplementedException();
        }
        public CommonResult GeneralSendTicketsNumAndPackageWeight(TicketInfo info)
        {
            throw new NotImplementedException();
        }
        public bool SendTicketsNumAndPackageWeight(string barcode, double weight, double length, double width, double height, double volume)
        {
            //Define the absolute path of the image            //var ListImage =  + @"\" + ("yyyyMMdd") + @"\" + barcode + ".jpg";
            try
            {
                Image upload
                DSuPicUpload = new Thread(() =&gt; UploadPic(barcode));
                ();
                return true;
            }
            catch (Exception ex)
            {
                Logger&lt;HanGuoLogisticsPic&gt;.Error("Thread start exception," + );
                return false;
            }
        }
        public T SendTicketsNumAndPackageWeight&lt;T&gt;(Dictionary&lt;string, object&gt; packageDic)
        {
            throw new NotImplementedException();
        }
        #region Image reporting interface        private void UploadPic(string barcode)
        {
            while (true)
            {
                if ( == 1)
                {
                    //Upload the picture                    DoLocalImgUpload((, ("yyyyMMdd")), barcode);
                    DoLocalImgUpload((, (-1).ToString("yyyyMMdd")), barcode);
                }
                (3000);
            }
        }
        public void DoLocalImgUpload(string picFilepath, string barcode)
        {
            try
            {
                if ((picFilepath))
                {
                    DirectoryInfo directoryInfo = new DirectoryInfo(picFilepath);
                    //Pick the first 5 pictures 1 minute ago in the picture folder (sorted by creation time)                    //Prevent files from being occupied                    lock (_loc)
                    {
                        var topfiles = ().
                        Where(p =&gt;  &lt;= (-1)).
                        OrderBy(f =&gt; ).
                        Take(5).ToList();
                        //  ();
                        (x =&gt; ).Distinct();
                        if ( &gt; 0)
                        {
                            //Loop execution upload                            foreach (var fileInfo in topfiles)
                            // for (var i = 0; i &lt; ; i++)
                            {
                                Logger&lt;HanGuoLogisticsPic&gt;.Debug(":" +  + "  fileInfo:" + );
                                UploadLocalByName(, barcode);
                                //(fileInfo);
                            }
                            ();
                            (1000);
                            Logger&lt;HanGuoLogisticsPic&gt;.Debug("The image upload thread is uploading loop!");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Logger&lt;HanGuoLogisticsPic&gt;.Error(".Exception occurred when uploading the image file!", ex);
            }
        }
        public void UploadLocalByName(string picFilepath, string barcode)
        {
            string url = @"/SendPackageInfo/ApiPhoto_I.asp";
            try
            {
                Logger&lt;HanGuoLogisticsPic&gt;.Debug("picFilepath:" + picFilepath);
                if ((picFilepath))
                {
                    int pos = ("\\");
                    string name = (pos + 1);
                    string nums = (".jpg", "");
                    //string userPhoto = ;
                    //byte[] bytes = (picFilepath);
                    //userPhoto = Convert.ToBase64String(bytes);
                    //userPhoto = ("+", "%2B");
                    if (UploadImages(nums, name, picFilepath, url, barcode))
                    {
                        //Does it need to be deleted after uploading?                        (picFilepath);
                    }
                }
            }
            catch (Exception ex)
            {
                Logger&lt;HanGuoLogisticsPic&gt;.Error(".Exception occurred when uploading the image file!", ex);
            }
        }
        public bool UploadImages(string code, string name, string picFilepath, string url, string barcode)
        {
            try
            {
                string result = SendData(picFilepath, name, url, barcode, null, null);
                var i = (result);
                if (i["result"].ToString().Trim() == "true")
                {
                    //Play sound file                    string strPath = (, @"config\sound") + "\\" + "";
                    if ((strPath))
                    {
                         sndPlayer2 = new (strPath);
                        ();
                    }
                    else
                    {
                        Logger&lt;HanGuoLogistics&gt;.Error("PlaySoundSendSuccess. The sound file does not exist:" + strPath);
                    }
                    return true;
                }
                else
                {
                    //Play sound file                    string strPath = (, @"config\sound") + "\\" + "";
                    if ((strPath))
                    {
                         sndPlayer2 = new (strPath);
                        ();
                    }
                    else
                    {
                        Logger&lt;HanGuoLogistics&gt;.Error("PlaySoundSendSuccess. The sound file does not exist:" + strPath);
                    }
                    return false;
                }
            }
            catch (Exception e)
            {
                Logger&lt;HanGuoLogisticsPic&gt;.Error("Uploading an image exception" + e);
            }
            return false;
        }
        public string SendData(string picFilepath, string name, string url, string barcode, string workConsole, string destination)
        {
            var fileContent1 = new ByteArrayContent((picFilepath));
             = new ContentDispositionHeaderValue("file")
            {
                FileName = name
            };
            var postContent = new MultipartFormDataContent();
            (new StringContent(barcode), "ticketsNum");
            (fileContent1);//Picture File            (new StringContent(workConsole), "workConsole");
            (new StringContent(destination), "destination");
            Logger&lt;HanGuoLogisticsPic&gt;.Debug("Towards"++"Send data"+(postContent));
            string httpResult = GetHttpPostResponse(url, postContent);
            Logger&lt;HanGuoLogisticsPic&gt;.Debug("take over" +  + "Return data" + httpResult);
            return httpResult;
        }
        private string GetHttpPostResponse(string url, MultipartFormDataContent postData)
        {
            string result = "";
            //Form form format parameter transfer            try
            {
                HttpClient client = new HttpClient();
                HttpResponseMessage response = (url, postData).Result;
                result = ().Result;
            }
            catch (Exception ex)
            {
                result = ;
            }
            Logger&lt;HanGuoLogisticsPic&gt;.Debug($"HanGuoLogistics Return data:{result}");
            return result;
        }
        /// &lt;summary&gt;
        /// Parameter reporting        /// &lt;/summary&gt;
        public class ImageInfo
        {
            public string ticketsNum { get; set; }
            public string file { get; set; }
            public string workConsole { get; set; }
            public string destination { get; set; }
        }
        /// &lt;summary&gt;
        /// Return information        /// &lt;/summary&gt;
        public class ImageResult
        {
            public bool result { get; set; }
            public string message { get; set; }
        }
        #endregion
    }
}

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