c# HTTP/HTTPS 文件上传。

方法主体
public static string MyUploader(string strFileToUpload, string strUrl, string strFileFormName, NameValueCollection querystring, CookieContainer cookies)
        {
            string postdata;
            postdata = "?";
            if (querystring != null)
            {
                foreach (string key in querystring.Keys)
                {
                    postdata += key + "=" + querystring.Get(key) + "&";
                }
            }
            //Uri uri = new Uri(strUrl + postdata);

            Uri oUri = new Uri(strUrl + postdata);

            string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");

            // The trailing boundary string
            byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n");

            // The post message header
            StringBuilder sb = new StringBuilder();
            sb.Append("--");
            sb.Append(strBoundary);
            sb.Append("\r\n");
            sb.Append("Content-Disposition: form-data; name=\"");
            sb.Append(strFileFormName);
            sb.Append("\"; filename=\"");
            sb.Append(Path.GetFileName(strFileToUpload));
            sb.Append("\"");
            sb.Append("\r\n");
            sb.Append("Content-Type: ");
            sb.Append("application/octet-stream");
            sb.Append("\r\n");
            sb.Append("\r\n");
            string strPostHeader = sb.ToString();
            byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader);

            // The WebRequest
            HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri);

            //如果是发送HTTPS请求  
            if (strUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase))
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                oWebrequest = WebRequest.Create(oUri) as HttpWebRequest;
                oWebrequest.ProtocolVersion = HttpVersion.Version10;
            }
            else
            {
                oWebrequest = WebRequest.Create(oUri) as HttpWebRequest;
            }

            oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary;
            oWebrequest.Method = "POST";

            // This is important, otherwise the whole file will be read to memory anyway...
            oWebrequest.AllowWriteStreamBuffering = false;

            // Get a FileStream and set the final properties of the WebRequest
            FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read);
            long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length;
            oWebrequest.ContentLength = length;
            Stream oRequestStream = oWebrequest.GetRequestStream();

            // Write the post header
            oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);

            // Stream the file contents in small pieces (4096 bytes, max).
            byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))];
            int bytesRead = 0;
            while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0)
                oRequestStream.Write(buffer, 0, bytesRead);
            oFileStream.Close();

            // Add the trailing boundary
            oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
            WebResponse oWResponse = oWebrequest.GetResponse();
            Stream s = oWResponse.GetResponseStream();
            StreamReader sr = new StreamReader(s);
            String sReturnString = sr.ReadToEnd();

            // Clean up
            oFileStream.Close();
            oRequestStream.Close();
            s.Close();
            sr.Close();

            return sReturnString;
        }
 
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
调用方法
            CookieContainer cookies = new CookieContainer();
            //add or use cookies  
            NameValueCollection querystring = new NameValueCollection();
            querystring["login_id"] = "your userid";
            querystring["password"] = "your password";
            string uploadfile = @"C:\Test.zip";// set to file to upload  
            string outdata = MyUploader(filePath, updateUrl, "zipfile", querystring, cookies);
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值