c# HTTP/HTTPS 文件上传。

分类: .net 2015-02-03 08:36 541人阅读 评论(0) 收藏 举报

方法主体

[csharp] view plaincopy

  1. public static string MyUploader(string strFileToUpload, string strUrl, string strFileFormName, NameValueCollection querystring, CookieContainer cookies) 
  2.         { 
  3. string postdata; 
  4.             postdata = "?"; 
  5. if (querystring != null) 
  6.             { 
  7. foreach (string key in querystring.Keys) 
  8.                 { 
  9.                     postdata += key + "=" + querystring.Get(key) + "&"; 
  10.                 } 
  11.             } 
  12. //Uri uri = new Uri(strUrl + postdata);
  13.             Uri oUri = new Uri(strUrl + postdata); 
  14. string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x"); 
  15. // The trailing boundary string
  16. byte[] boundaryBytes = Encoding.ASCII.GetBytes("\r\n--" + strBoundary + "\r\n"); 
  17. // The post message header
  18.             StringBuilder sb = new StringBuilder(); 
  19.             sb.Append("--"); 
  20.             sb.Append(strBoundary); 
  21.             sb.Append("\r\n"); 
  22.             sb.Append("Content-Disposition: form-data; name=\""); 
  23.             sb.Append(strFileFormName); 
  24.             sb.Append("\"; filename=\""); 
  25.             sb.Append(Path.GetFileName(strFileToUpload)); 
  26.             sb.Append("\""); 
  27.             sb.Append("\r\n"); 
  28.             sb.Append("Content-Type: "); 
  29.             sb.Append("application/octet-stream"); 
  30.             sb.Append("\r\n"); 
  31.             sb.Append("\r\n"); 
  32. string strPostHeader = sb.ToString(); 
  33. byte[] postHeaderBytes = Encoding.UTF8.GetBytes(strPostHeader); 
  34. // The WebRequest
  35.             HttpWebRequest oWebrequest = (HttpWebRequest)WebRequest.Create(oUri); 
  36. //如果是发送HTTPS请求 
  37. if (strUrl.StartsWith("https", StringComparison.OrdinalIgnoreCase)) 
  38.             { 
  39.                 ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult); 
  40.                 oWebrequest = WebRequest.Create(oUri) as HttpWebRequest; 
  41.                 oWebrequest.ProtocolVersion = HttpVersion.Version10; 
  42.             } 
  43. else
  44.             { 
  45.                 oWebrequest = WebRequest.Create(oUri) as HttpWebRequest; 
  46.             } 
  47.             oWebrequest.ContentType = "multipart/form-data; boundary=" + strBoundary; 
  48.             oWebrequest.Method = "POST"; 
  49. // This is important, otherwise the whole file will be read to memory anyway...
  50.             oWebrequest.AllowWriteStreamBuffering = false; 
  51. // Get a FileStream and set the final properties of the WebRequest
  52.             FileStream oFileStream = new FileStream(strFileToUpload, FileMode.Open, FileAccess.Read); 
  53. long length = postHeaderBytes.Length + oFileStream.Length + boundaryBytes.Length; 
  54.             oWebrequest.ContentLength = length; 
  55.             Stream oRequestStream = oWebrequest.GetRequestStream(); 
  56. // Write the post header
  57.             oRequestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length); 
  58. // Stream the file contents in small pieces (4096 bytes, max).
  59. byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)oFileStream.Length))]; 
  60. int bytesRead = 0; 
  61. while ((bytesRead = oFileStream.Read(buffer, 0, buffer.Length)) != 0) 
  62.                 oRequestStream.Write(buffer, 0, bytesRead); 
  63.             oFileStream.Close(); 
  64. // Add the trailing boundary
  65.             oRequestStream.Write(boundaryBytes, 0, boundaryBytes.Length); 
  66.             WebResponse oWResponse = oWebrequest.GetResponse(); 
  67.             Stream s = oWResponse.GetResponseStream(); 
  68.             StreamReader sr = new StreamReader(s); 
  69.             String sReturnString = sr.ReadToEnd(); 
  70. // Clean up
  71.             oFileStream.Close(); 
  72.             oRequestStream.Close(); 
  73.             s.Close(); 
  74.             sr.Close(); 
  75. return sReturnString; 
  76.         } 

[csharp] view plaincopy

  1. private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors) 
  2.         { 
  3. return true; //总是接受 
  4.         } 

调用方法

[csharp] view plaincopy

  1. CookieContainer cookies = new CookieContainer(); 
  2. //add or use cookies 
  3. NameValueCollection querystring = new NameValueCollection(); 
  4. querystring["login_id"] = "your userid"; 
  5. querystring["password"] = "your password"; 
  6. string uploadfile = @"C:\Test.zip";// set to file to upload 
  7. string outdata = MyUploader(filePath, updateUrl, "zipfile", querystring, cookies);

个人收藏--未整理—C# http/https 上传下载文件的更多相关文章

  1. 向linux服务器上传下载文件方式收集

    向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...

  2. C#实现http协议支持上传下载文件的GET、POST请求

    C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...

  3. HttpClient上传下载文件

    HttpClient上传下载文件 java HttpClient Maven依赖 <dependency> <groupId>org.apache.httpcomponents ...

  4. 【WCF】利用WCF实现上传下载文件服务

    引言     前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...

  5. springboot整合vue实现上传下载文件

    https://blog.csdn.net/yhhyhhyhhyhh/article/details/89888953 文章目录 springboot整合vue实现上传下载文件 1上传下载文件api文 ...

  6. 上传下载文件到Linux服务器

    转自链接:https://blog.csdn.net/drdongshiye/article/details/89430535Mac的终端是十分强大 , 可以通过命令进行上传下载下载文件夹 scp - ...

  7. 【转】Java IOUtils方式上传下载文件 on HDFS

    [From]https://www.cnblogs.com/areyouready/p/9795442.html package com.css.hdfs04; import java.io.File ...

  8. Jmeter 上传下载文件

    最近很多同学都在问jmeter上传.下载文件的脚本怎么做,要压测上传.下载文件的功能,脚本怎么做,网上查了都说的很含糊,这次呢,咱们就好好的把jmeter的上传下载文件好好缕缕,都整明白了,怎么个过程 ...

  9. rz和sz上传下载文件工具lrzsz

    ######################### rz和sz上传下载文件工具lrzsz ####################################################### ...

随机推荐

  1. python str的一些操作及处理

    一.str的定义:Python中凡是用引号引起来的数据可以称为字符串类型,组成字符串的每个元素称之为字符,将这些字符一个一个连接起来,然后在用引号起来就是字符串. 二.str的简单操作方法: conu ...

  2. django & celery - 关于并发处理能力和内存使用的小结

    背景 众所周知,celery 是python世界里处理分布式任务的好助手,它的出现结合赋予了我们强大的处理异步请求,分布式任务,周期任务等复杂场景的能力. 然鹅,今天我们所要讨论的则是如何更好的在使用 ...

  3. C++学习笔记11_STL

    STL又叫标准模板库,提供各种容器. STL是C++一部分,不休要额外安装什么,它被内建在编译器之内. STL重要特点是,数据结构和实现分离. *所谓迭代器,类似一个游标,使用++指向下一个元素,使用 ...

  4. python super原理,不是指父类

    class a(object): def __init__(self): print('in a') class b(a): def __init__(self): print('in b') sup ...

  5. 单点登录 - API 认证系统 Passport(二)

    安装 composer require laravel/passport=~4.0 notes: 1)确保系统安装unzip.zip等命令. 2)composer 安装出现 Authenticatio ...

  6. 如何在双向绑定的Image控件上绘制自定义标记(wpf)

    我们的需求是什么? 答:需要在图片上增加一些自定义标记,例如:2个图片对比时,对相同区域进行高亮. 先上效果图: 设计思路 1.概述 1.通过TargeUpdated事件,重新绘制图片进行替换. 2. ...

  7. python之小木马(文件上传,下载,调用命令行,按键监控记录)

    window版 服务端: 开启两个线程,一个用来接收客户端的输入,一个用来监控服务端键盘的记录 客户端: get 文件(下载)put 文件(上传) window下cmd命令执行结果会直接打印出来,ke ...

  8. 底半部之工作队列和tasklet,内核定时器。

    1.软中断机制  不能以模块形式出现   使用起来不够灵活2.tasklet  核心数据结构       struct tasklet_struct      {          function  ...

  9. python——int()、hex()、oct()、bin()、float()数值类型转换函数

    摘要:在python中,数值类型转换函数常用的有浮点型float().取整int().八进制oct().二进制bin().十六进制hex()这五个函数. 单词float的意思就是浮动的意思: int是 ...

  10. ios jquery css('left')无法读取属性解决的方法

    ios jquery css('left')无法读取属性解决的方法 <pre>$(this).position().left因为display:none状态下是读取不了 $(this).o ...