打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
C#模拟POST上传文件帮助类(支持https、http)

 public static int PostFile(string getUrl, CookieContainer cookieContainer, HttpHeader header, string postdata, byte[] postdatabyte, Stream sm)
        {
            Stream fileStream;
            if (sm != null)
            {
                fileStream = sm;
            }
            else
            {
                fileStream = new MemoryStream(postdatabyte);
            }
            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls;//https形式需要添加
            int returnValue = 0;
            fileStream.Position = 0;
            var r = new BinaryReader(fileStream);
            string strBoundary = "--"+ DateTime.Now.Ticks.ToString("x");
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "--\r\n");
            //请求头部信息
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"importType\"");
            sb.Append("\r\n\r\n1");
            sb.Append("\r\n");
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"file\"; filename=\"1.xls\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n\r\n");
            string strPostHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);
            try
            {
                // 根据uri创建HttpWebRequest对象
                HttpWebRequest httpReq = (HttpWebRequest)WebRequest.Create(new Uri(getUrl));
                httpReq.Method = "POST";
                //对发送的数据不使用缓存
                httpReq.AllowWriteStreamBuffering = false;
                //设置获得响应的超时时间(300秒)
                httpReq.Timeout = 300000;
                //httpReq.ServicePoint.Expect100Continue = false;
                httpReq.CookieContainer = cookieContainer;
                httpReq.Accept = header.accept;
                //httpReq.Headers.Add("Accept-Encoding","gzip, deflate, br");
                //httpReq.Headers.Add("TE", "Trailers");
                httpReq.UserAgent = header.userAgent;
                httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;
                long length = fileStream.Length + postHeaderBytes.Length + boundaryBytes.Length;
                long fileLength = fileStream.Length;
                httpReq.ContentLength = length;
                byte[] buffer = new byte[fileLength];
                Stream postStream = httpReq.GetRequestStream();
                //发送请求头部消息
                postStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
                int size = r.Read(buffer, 0, buffer.Length);
                postStream.Write(buffer, 0, size);
                //添加尾部的时间戳
                postStream.Write(boundaryBytes, 0, boundaryBytes.Length);
                postStream.Close();
                //获取服务器端的响应
                HttpWebResponse webRespon = (HttpWebResponse)httpReq.GetResponse();
                if (webRespon.StatusCode == HttpStatusCode.OK) //如果服务器未响应,那么继续等待相应                 
                {
                    Stream s = webRespon.GetResponseStream();
                    StreamReader sr = new StreamReader(s);
                    //读取服务器端返回的消息
                    String sReturnString = sr.ReadLine();
                    s.Close();
                    sr.Close();
                    fileStream.Close();
                 returnValue=returnValue;
                }
            }
            catch (Exception ex)
            {
                UnionLog.WriteLog(LogType.UNION_ERROR, string.Format("导入Excel失败:{0}", ex.Message));
            }
            return returnValue;
        }

 

特别注意:代码中包括“--”的地方不可以随意更改,否则踩坑。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
如何写出安全的API接口?接口参数加密签名设计思路
Windows Phone 7下一个上传图片的类_银光中国 Silverlight 资源 ...
C#IO文件读写和流
给定一字符数组,求数组中字符组成的所有排列? - Java / Java SE
一个巧妙的正则验证
C# 实现Escape UnEscape方法(支持中文
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服