个人收藏--未整理—C# http/https 上传下载文件
c# HTTP/HTTPS 文件上传。
分类: .net 2015-02-03 08:36 541人阅读 评论(0) 收藏 举报
方法主体
[csharp] view plaincopy
- 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;
- }
[csharp] view plaincopy
- private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
- {
- return true; //总是接受
- }
调用方法
[csharp] view plaincopy
- 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);
个人收藏--未整理—C# http/https 上传下载文件的更多相关文章
- 向linux服务器上传下载文件方式收集
向linux服务器上传下载文件方式收集 1. scp [优点]简单方便,安全可靠:支持限速参数[缺点]不支持排除目录[用法] scp就是secure copy,是用来进行远程文件拷贝的.数据传输使用 ...
- C#实现http协议支持上传下载文件的GET、POST请求
C#实现http协议支持上传下载文件的GET.POST请求using System; using System.Collections.Generic; using System.Text; usin ...
- HttpClient上传下载文件
HttpClient上传下载文件 java HttpClient Maven依赖 <dependency> <groupId>org.apache.httpcomponents ...
- 【WCF】利用WCF实现上传下载文件服务
引言 前段时间,用WCF做了一个小项目,其中涉及到文件的上传下载.出于复习巩固的目的,今天简单梳理了一下,整理出来,下面展示如何一步步实现一个上传下载的WCF服务. 服务端 1.首先新建一个名 ...
- springboot整合vue实现上传下载文件
https://blog.csdn.net/yhhyhhyhhyhh/article/details/89888953 文章目录 springboot整合vue实现上传下载文件 1上传下载文件api文 ...
- 上传下载文件到Linux服务器
转自链接:https://blog.csdn.net/drdongshiye/article/details/89430535Mac的终端是十分强大 , 可以通过命令进行上传下载下载文件夹 scp - ...
- 【转】Java IOUtils方式上传下载文件 on HDFS
[From]https://www.cnblogs.com/areyouready/p/9795442.html package com.css.hdfs04; import java.io.File ...
- Jmeter 上传下载文件
最近很多同学都在问jmeter上传.下载文件的脚本怎么做,要压测上传.下载文件的功能,脚本怎么做,网上查了都说的很含糊,这次呢,咱们就好好的把jmeter的上传下载文件好好缕缕,都整明白了,怎么个过程 ...
- rz和sz上传下载文件工具lrzsz
######################### rz和sz上传下载文件工具lrzsz ####################################################### ...
随机推荐
- python str的一些操作及处理
一.str的定义:Python中凡是用引号引起来的数据可以称为字符串类型,组成字符串的每个元素称之为字符,将这些字符一个一个连接起来,然后在用引号起来就是字符串. 二.str的简单操作方法: conu ...
- django & celery - 关于并发处理能力和内存使用的小结
背景 众所周知,celery 是python世界里处理分布式任务的好助手,它的出现结合赋予了我们强大的处理异步请求,分布式任务,周期任务等复杂场景的能力. 然鹅,今天我们所要讨论的则是如何更好的在使用 ...
- C++学习笔记11_STL
STL又叫标准模板库,提供各种容器. STL是C++一部分,不休要额外安装什么,它被内建在编译器之内. STL重要特点是,数据结构和实现分离. *所谓迭代器,类似一个游标,使用++指向下一个元素,使用 ...
- python super原理,不是指父类
class a(object): def __init__(self): print('in a') class b(a): def __init__(self): print('in b') sup ...
- 单点登录 - API 认证系统 Passport(二)
安装 composer require laravel/passport=~4.0 notes: 1)确保系统安装unzip.zip等命令. 2)composer 安装出现 Authenticatio ...
- 如何在双向绑定的Image控件上绘制自定义标记(wpf)
我们的需求是什么? 答:需要在图片上增加一些自定义标记,例如:2个图片对比时,对相同区域进行高亮. 先上效果图: 设计思路 1.概述 1.通过TargeUpdated事件,重新绘制图片进行替换. 2. ...
- python之小木马(文件上传,下载,调用命令行,按键监控记录)
window版 服务端: 开启两个线程,一个用来接收客户端的输入,一个用来监控服务端键盘的记录 客户端: get 文件(下载)put 文件(上传) window下cmd命令执行结果会直接打印出来,ke ...
- 底半部之工作队列和tasklet,内核定时器。
1.软中断机制 不能以模块形式出现 使用起来不够灵活2.tasklet 核心数据结构 struct tasklet_struct { function ...
- python——int()、hex()、oct()、bin()、float()数值类型转换函数
摘要:在python中,数值类型转换函数常用的有浮点型float().取整int().八进制oct().二进制bin().十六进制hex()这五个函数. 单词float的意思就是浮动的意思: int是 ...
- ios jquery css('left')无法读取属性解决的方法
ios jquery css('left')无法读取属性解决的方法 <pre>$(this).position().left因为display:none状态下是读取不了 $(this).o ...