c# HTTP Post上传文件与表格 ContentType = “multipart/form-data“

新建HttpUpload.Core项目

UploadParameterType类

    public static class HttpCode
    {
        /// <summary>
        /// 上传超时项
        /// </summary>
        public static string ResponseTimeout = "-1624";
    }
    /// <summary>
    /// 上传文件 - 请求参数类
    /// </summary>
    public class UploadParameterType
    {
        public UploadParameterType()
        {
            FileNameKey = "file";
            Encoding = Encoding.UTF8;
            PostParameters = new Dictionary<string, string>();
        }
        /// <summary>
        /// 上传地址
        /// </summary>
        public string Url { get; set; }
        /// <summary>
        /// 文件名称key
        /// </summary>
        public string FileNameKey { get; set; }
        /// <summary>
        /// 文件名称value
        /// </summary>
        public string FileNameValue { get; set; }
        /// <summary>
        /// 编码格式
        /// </summary>
        public Encoding Encoding { get; set; }
        /// <summary>
        /// 上传文件的流
        /// </summary>
        public Stream UploadStream { get; set; }
        /// <summary>
        /// 上传文件 携带的参数集合
        /// </summary>
        public IDictionary<string, string> PostParameters { get; set; } 
    }

HttpUploadClient类

/// <summary>
    /// Http上传文件类 - HttpWebRequest封装
    /// </summary>
    public class HttpUploadClient
    {
        /// <summary>
        /// 上传执行 方法
        /// </summary>
        /// <param name="parameter">上传文件请求参数</param>
        public static string Execute(UploadParameterType parameter)
        {
            using (MemoryStream memoryStream = new MemoryStream())
            {
                // 1.分界线
                string boundary = string.Format("--------------------------{0}", DateTime.Now.Ticks.ToString("x")),       // 分界线可以自定义参数
                    beginBoundary = string.Format("--{0}\r\n", boundary),
                    endBoundary = string.Format("\r\n--{0}--\r\n", boundary);
                byte[] beginBoundaryBytes = parameter.Encoding.GetBytes(beginBoundary),
                    endBoundaryBytes = parameter.Encoding.GetBytes(endBoundary);
                // 2.组装开始分界线数据体 到内存流中
                memoryStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);
                // 3.组装 上传文件附加携带的参数 到内存流中
                if (parameter.PostParameters != null && parameter.PostParameters.Count > 0)
                {
                    foreach (KeyValuePair<string, string> keyValuePair in parameter.PostParameters)
                    {
                        string parameterHeaderTemplate = string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n{2}", keyValuePair.Key, keyValuePair.Value, beginBoundary);
                        byte[] parameterHeaderBytes = parameter.Encoding.GetBytes(parameterHeaderTemplate);

                        memoryStream.Write(parameterHeaderBytes, 0, parameterHeaderBytes.Length);
                    }
                }
                // 4.组装文件头数据体 到内存流中
                string fileHeaderTemplate = string.Format("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: application/octet-stream\r\n\r\n", parameter.FileNameKey, parameter.FileNameValue);
                byte[] fileHeaderBytes = parameter.Encoding.GetBytes(fileHeaderTemplate);
                memoryStream.Write(fileHeaderBytes, 0, fileHeaderBytes.Length);
                // 5.组装文件流 到内存流中
                int fsLen = (int)parameter.UploadStream.Length;
                byte[] buffer = new byte[fsLen];
                int size = parameter.UploadStream.Read(buffer, 0, buffer.Length);
                while (size > 0)
                {
                    memoryStream.Write(buffer, 0, size);
                    size = parameter.UploadStream.Read(buffer, 0, buffer.Length);
                }
                // 6.组装结束分界线数据体 到内存流中
                memoryStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
                // 7.获取二进制数据
                byte[] postBytes = memoryStream.ToArray();
                // 8.HttpWebRequest 组装
                HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(new Uri(parameter.Url, UriKind.RelativeOrAbsolute));
                webRequest.Method = "POST";
                webRequest.Timeout = 10000;
                webRequest.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                webRequest.ContentLength = postBytes.Length;
                if (Regex.IsMatch(parameter.Url, "^https://"))
                {
                    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;
                    ServicePointManager.ServerCertificateValidationCallback = CheckValidationResult;
                }
                // 9.写入上传请求数据
                using (Stream requestStream = webRequest.GetRequestStream())
                {
                    requestStream.Write(postBytes, 0, postBytes.Length);
                    requestStream.Close();
                }
                try
                {
                    // 10.获取响应
                    using (HttpWebResponse webResponse = (HttpWebResponse)webRequest.GetResponse())
                    {
                        using (StreamReader reader = new StreamReader(webResponse.GetResponseStream(), parameter.Encoding))
                        {
                            string body = reader.ReadToEnd();
                            reader.Close();
                            return body;
                        }
                    }
                }
                catch (Exception)
                {
                    string errorstr = string.Format("{{\"msg\":\"响应超时\",\"code\":{0}}}", HttpCode.ResponseTimeout);
                    return errorstr;
                }
            }
        }
        static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true;
        }
    }

调用方法,我把调用的方法写成了一个函数,如果有需要可以自行修改

        /// <summary>
        /// 使用post上传json表格和文件,ContentType = "multipart/form-data"
        /// </summary>
        /// <param name="URL">服务器路径</param>
        /// <param name="FileName">文件名</param>
        /// <param name="jsonstr">表格</param>
        /// <param name="FilePath">文件路径</param>
        /// <returns></returns>
        public static string PostIQ(string URL, string FileName, string jsonstr, string FilePath)
        {
            using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
            {
                IDictionary<string, string> postParameter = new Dictionary<string, string>();
                postParameter.Add("entity", jsonstr);//表格名称
                string result = HttpUploadClient.Execute(new UploadParameterType
                {
                    Url = URL,
                    UploadStream = fileStream,
                    FileNameValue = FileName,
                    PostParameters = postParameter
                });
                return result;
            }
        }

使用示例

            string URL = "http://192.16.22.166:8888/aaaa/xxxx/remote";
            string FileName = "文件名.txt";
            string jsonstr = string.Format("{{\"参数1\":\"111\",\"参数2\":\"222\"}}", FileName);
            string FilePath = @"D:\Desktop\" + FileName;
            string sss = UploadFunction.PostIQ(URL, FileName, jsonstr, FilePath);

接收后还可以通过code的返回值来判断文件上传的结果

参考来源https://www.cnblogs.com/GodX/p/5604944.html

因为一开始没有测试通过  所以在原代码上略做改变,接口测试软件用的ApiPost

代码下载https://download.csdn.net/download/www89574622/15711112

上一篇:详解JavaScript中的Url编码/解码,表单提交中网址编码


下一篇:python中收集参数