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;
        }

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

C#模拟POST上传文件帮助类(支持https、http)的更多相关文章

  1. Java模拟http上传文件请求(HttpURLConnection,HttpClient4.4,RestTemplate)

    先上代码: public void uploadToUrl(String fileId, String fileSetId, String formUrl) throws Throwable { St ...

  2. ApiPost接口调试工具模拟Post上传文件(中文版Postman)

    ApiPost简介: ApiPost是一个支持团队协作,并可直接生成文档的API调试.管理工具.它支持模拟POST.GET.PUT等常见请求,是后台接口开发者或前端.接口测试人员不可多得的工具 . A ...

  3. c# 模拟POST上传文件到服务器

    using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...

  4. (实用篇)PHP ftp上传文件操作类

    <?php /** * 作用:FTP操作类( 拷贝.移动.删除文件/创建目录 ) */ class class_ftp { public $off; // 返回操作状态(成功/失败) publi ...

  5. 通过WebClient模拟post上传文件到服务器

    写在前面 最近一直在研究sharepoint的文档库,在上传文件到文档库的过程中,需要模拟post请求,也查找了几种模拟方式,webclient算是比较简单的方式. 一个例子 这里写一个简单接受pos ...

  6. 通过PHP CURL模拟请求上传文件|图片。

    现在有一个需求就是在自己的服务器上传图片到其他服务器上面,过程:客户端上传图片->存放到本地服务器->再转发到第三方服务器; 由于前端Ajax受限制,只能通过服务器做转发了. 在PHP中通 ...

  7. PHP -- 模拟测试上传文件

    FROM :http://web.itivy.com/article-740-1.html QQ上传文件为什么那么快? “QQ上传大文件/QQ群发送大文件时,可以在极短的时间内完成”是如何做到的. 有 ...

  8. 用iFrame模拟Ajax上传文件

    前段时间在解决ajax上传文件时折腾了好一阵.直接用$.post上传文本信息肯定是没有问题的.但是$.post直接上传图片是不可行的. 后来看到网上的一些解决方案,有现成的ajax上传文件的封装的方法 ...

  9. PHP curl 模拟POST 上传文件(含php 5.5后CURLFile)

    <?php /** * Email net.webjoy@gmail.com * author jackluo * 2014.11.21 * */ //* function curl_post( ...

随机推荐

  1. LeetCode动画 | 1038. 从二叉搜索树到更大和树

    今天分享一个LeetCode题,题号是1038,标题是:从二分搜索树到更大和数. 题目描述 给出二叉搜索树的根节点,该二叉树的节点值各不相同,修改二叉树,使每个节点 node 的新值等于原树中大于或等 ...

  2. Docker windows nanoserver/mysql镜像root用户密码错误

    由于需要在Windows server上的Docker中部署mysql服务,为了方便起见所以在Docker hub找到了nanoserver/mysql (https://hub.docker.com ...

  3. 使用eNSP配置QinQ

    参考链接:https://blog.csdn.net/alone_map/article/details/52217094 本文主要记录使用华为eNSP模拟器来实现配置QinQ,并对QinQ的报文进行 ...

  4. laravel脚手架搭建项目问题之生产环境element-ui组件字体图标显示错误问题

    问题描述: 1.element-ui组件使用的是npm安装 2.npm scripe模式开发 3.使用git命令行工具开发 3.开发环境下图标正常显示 4.生产环境下图标显示不正常 分析原因: 图标文 ...

  5. [集训]Evocation

    题意 一颗有根树,每个点有黑白两种颜色和阀值ai,若它的子树中(不包括自己)的黑色数量大于ai,则产生一点贡献.每次将一个点的颜色取反,求每次修改后的贡献.n,q<=1E5. 思考 树剖后直接分 ...

  6. Can you answer these queries III(线段树)

    Can you answer these queries III(luogu) Description 维护一个长度为n的序列A,进行q次询问或操作 0 x y:把Ax改为y 1 x y:询问区间[l ...

  7. AOP编程实践总结

    AOP编程实践总结 AOP概述 AOP(Aspect-Oriented Programming,面向方面编程)是OOP(Object-Oriented Programing,面向对象编程)的补充和完善 ...

  8. SpringBoot任务篇Ⅴ --- 异步任务、定时任务、邮件任务

    Java的任务在项目中需要用到的地方很多,比如,每月月末的财务报表给财务部门,定时给领导发个邮件短信等等.这时候我们就需要用到任务了,任务调度本身涉及到多线程并发.运行时间规则制定和解析.场景保持与恢 ...

  9. 使用IDEA构建Spring-boot多模块项目配置流程

    使用IDEA构建Spring-boot多模块项目配置流程 1.创建项目 点击Create New Project 在左侧选中Spring Initializer,保持默认配置,点击下一步. 在Grou ...

  10. nginx的进程结构实例演示

    nginx父子进程之间是使用信号进行管理的. nginx -s reload 会使之前的nginx子进程退出,生成新的nginx子进程 或者kill -SIGHUP 9170 kill -SIGTER ...