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. 关于kaggle注册无法显示人机验证码问题

    最近准备做项目,需要在kaggle上下载数据集,但注册时遇到了无法显示验证图片信息的问题,我也是通过百度最终找到解决方法,所以就准备记录下来啦:下面是解决步骤: step1:下载Google访问助手 ...

  2. 神舟+win10+ubuntu16.04+256GSSD+1THHD双系统安装加openssl踩坑之旅

    上海最近搞活动调休,要搞深度学习,win上还是不方便,准备弄个ubuntu.于是有以下回忆文字. 在机器上装了个双系统.花了两天.再也不想玩了. 准备用ubuntu来做深度学习的. 本文写于2019年 ...

  3. CSS3 变形、过渡、动画、关联属性浅析

    一.变形 transform:可以对元素对象进行旋转rotate.缩放scale.移动translate.倾斜skew.矩阵变形matrix.示例: transform: rotate(90deg) ...

  4. Leetcode算法【34在排序数组中查找元素】

    在之前ARTS打卡中,我每次都把算法.英文文档.技巧都写在一个文章里,这样对我的帮助是挺大的,但是可能给读者来说,一下子有这么多的输入,还是需要长时间的消化. 那我现在改变下方式,将每一个模块细分化, ...

  5. [知识图谱]利用py2neo从Neo4j数据库获取数据

    # -*- coding: utf-8 -*- from py2neo import Graph import json import re class Neo4jToJson(object): &q ...

  6. LNMP+Redis

    如果要让php支持redis需要安装php-redis模块.可以再github上下载哦. https://github.com/phpredis/phpredis 配置lnmp环境,太简单了就不演示了 ...

  7. 记录一些html5和css3的一部分属性

    html5 标签1 video:视频 属性: src:视频的url autoplay:视频在就绪后马上播放 controls:向用户显示控件2 audio:音频 属性类似于video3 属性:drag ...

  8. 【控制系统数字仿真与CAD】实验二:结构图法数字仿真

    一. 实验目的 1. 掌握结构图法仿真复杂控制系统的方法: 2. 掌握复杂系统联接矩阵W和输入联接矩阵W0的求解过程: 3. 掌握复杂系统的环节连接,矩阵A. B. C.D的求解过程: 4. 掌握MA ...

  9. JavaScrip 基础

    JavaScript 基础 前段的三剑客之一JS,来来来,看看它是什么鬼!到底如何让网页动起来的呢,今天就搞他一下. 一.JavaScript的简单介绍 javascript是一门动态弱类型的解释型编 ...

  10. 第六天、用户、组、权限、grep

    第六天.用户.组.权限.grep 权限总结表 操作 源目录权限 文件权限 目标目录权限 rm删文件 wx - - mv改名 wx - - mv移动文件 wx r wx cp复制文件 x r wx &g ...