C# 以Post方式multipart/form-data格式发送文件和参数

项目场景:

用C# 开发接口,接口需要上传文件,并且附带其他参数。


问题描述

跳了无数的坑才找到的可行的写法,分享给各位,希望能有所帮助。


解决方案:

直接上代码:

        /// <summary>
        /// 上传文件接口
        /// </summary>
        /// <param name="dictParam">上传参数</param>
        /// <param name="fileUrl">文件的地址</param>
        /// <param name="url">请求接口地址</param>
        /// <param name="encoding">字符编码格式</param>
        /// <param name="keyName">文件参数的参数名称</param>
        /// <returns></returns>
        public static string UploadRequest(Dictionary<string, object> dictParam,string fileUrl, Encoding encoding, string url ,string keyName )
        {
            
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
            WebHeaderCollection header = request.Headers;
            request.Method = "post";

            //读取文件信息
            FileStream fileStream = new FileStream(fileUrl, FileMode.Open, FileAccess.Read, FileShare.Read); 
            byte[] bytes = new byte[fileStream.Length];
            fileStream.Read(bytes, 0, bytes.Length);
            fileStream.Close();
            byte[] UpdateFile = bytes;//转换为二进制
            if (UpdateFile.Length == 0)
            {
                return "上传文件无效";
            }
            string Boundary = "--WebKitFormBoundary39B5a5e2FWoGbphs";
            //构造POST请求体
            StringBuilder PostContent = new StringBuilder("");

            //获取文件名称
            string filename = "";
            filename = Path.GetFileName(fileUrl);

            //组成普通参数信息
            foreach (KeyValuePair<string, object> item in dictParam)
            {
                    PostContent.Append("--" + Boundary + "\r\n")
                               .Append("Content-Disposition: form-data; name=\"" + item.Key + "\"" + "\r\n\r\n" + (string)item.Value + "\r\n");      
            }
            byte[] PostContentByte = encoding.GetBytes(PostContent.ToString());

            //处理文件参数信息
            StringBuilder FileContent = new StringBuilder();  
            FileContent.Append("--" + Boundary + "\r\n")
                    .Append("Content-Disposition:form-data; name=\"" + keyName + "\";filename=\"" + filename + "\"" + "\r\n\r\n");
            byte[] FileContentByte = encoding.GetBytes(FileContent.ToString());
            request.ContentType = "multipart/form-data;boundary=" + Boundary;
            byte[] ContentEnd = encoding.GetBytes("\r\n--" + Boundary + "--\r\n");//请求体末尾,后面会用到
            //定义请求流
            Stream myRequestStream = request.GetRequestStream();
            myRequestStream.Write(PostContentByte, 0, PostContentByte.Length);//写入参数
            myRequestStream.Write(FileContentByte, 0, FileContentByte.Length);//写入文件信息
            myRequestStream.Write(UpdateFile, 0, UpdateFile.Length);//文件写入请求流中
            myRequestStream.Write(ContentEnd, 0, ContentEnd.Length);//写入结尾   
            myRequestStream.Close();
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string encodingth = response.ContentEncoding;
            if (encodingth == null || encodingth.Length < 1)
            {
                encodingth = "GBK"; //默认编码,根据需求自己指定 
            }
            StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding(encodingth));
            string retString = reader.ReadToEnd();
            return retString;
        }

  • 4
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值