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. ORM之多表操作

    一.创建模型 from django.db import models # Create your models here. class Book(models.Model): nid = model ...

  2. Android_Fragment栈操作 commit()问题分析

    栈操作时遇到一个问题 getFragmentManager().beginTransaction() .replace(R.id.fl_container,bFragment) .addToBackS ...

  3. Nexus安装(Windows)

    1. nexus下载 官网下载:https://www.sonatype.com/download-oss-sonatype 网盘下载:https://pan.baidu.com/s/1CXOW7Lv ...

  4. Luogu P1816 忠诚

    rmq模板题.用st表切一个. 关于st表的详解见我的博客:st表.树状数组与线段树 笔记与思路整理 题目描述 老管家是一个聪明能干的人.他为财主工作了整整10年,财主为了让自已账目更加清楚.要求管家 ...

  5. [考试反思]1108csp-s模拟测试105: 傀儡

    评测机是真的老了... 我的脑力也老了... 昨天写完T3之后感觉脑子就留在那了,直到现在还感觉自己神志不清... T1OJ上过了(跑得挺慢但是的确过了),但是文件评测同样是开O2居然只剩下70分.. ...

  6. [考试反思]1015csp-s模拟测试74:压迫

    其实同时也是第27,一大片并列的. 真的是越考越烂. T1是个弱化的贪心原题,15分钟拿下没什么可说的. T2打的记忆化搜索,hash_mod太小撞哈希了,50->30 T3,想不到正解,90分 ...

  7. C/c.pp:贪心,二分答案

    说是贪心有点牵强. 其次,答案满足单调性,如果在k次操作能完成那么在k+1次操作内也能完成. 因为大不了你就把多的一次对方操作再进行一次就好了. 怎么操作呢? 我们从头扫这个序列,遇到每一个不匹配位置 ...

  8. 划艇:dp/组合数/区间离散化

    Description 在首尔城中,汉江横贯东西.在汉江的北岸,从西向东星星点点地分布着 N 个划艇学校,编号依次为 1 到 N.每个学校都拥有若干艘划艇.同一所学校的所有划艇颜色相同,不同的学校的划 ...

  9. Linux下安装jdk8步骤

    作为Java开发人员,在Linux下安装一些开发工具是必备技能,本文以安装jdk为例,详细记录了每一步的操作命令,以供参考. 下载jdk8 登录网址:http://www.oracle.com/tec ...

  10. Mybatis精讲(一)---环境配置及架构梳理

    目录 简介 ORM模型 Hibernate Ibatis 环境搭建 jar 配置 xml方式配置 代码方式配置 两种方式对比 Mybatis结构 源码解读xml环境加载 映射器解读 Ibatis # ...