C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法
作者:shichen2014 发布时间:2023-07-18 17:20:29
标签:C#,HttpWebRequest,HTTP
本文实例讲述了C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法,在项目开发中有一定的实用价值,具体方法如下:
一、前言:
这篇文章翻译来自madmik3 写在 CodeProject 上的文章,原标题为: C#'s WebClient.UploadFile with more functionality.
二、正文:
我们使用 WebRequest 来获取网页内容是非常简单的,可是用他来上传文件就没有那么简单了。
如果我们在网页中上传文件,加入下面代码即可:
HTML 文件上传代码实例:
<form action ="http://localhost/test.php" method = POST>
<input type = text name = uname>
<input type = password name =passwd>
<input type = FILE name = uploadfile>
<input type=submit>
</form>
但,如果在C#中使用 WebRequest 上传,必须对本地文件进行相应的处理才能提交到指定的HTTP地址,下面这个函数哦就帮我们做了这烦恼的操作
UploadFileEx 上传文件函数:
public static string UploadFileEx( string uploadfile, string url,
string fileFormName, string contenttype,NameValueCollection querystring,
CookieContainer cookies)
{
if( (fileFormName== null) ||
(fileFormName.Length ==0))
{
fileFormName = "file";
}
if( (contenttype== null) ||
(contenttype.Length ==0))
{
contenttype = "application/octet-stream";
}
string postdata;
postdata = "?";
if (querystring!=null)
{
foreach(string key in querystring.Keys)
{
postdata+= key +"=" + querystring.Get(key)+"&";
}
}
Uri uri = new Uri(url+postdata);
string boundary = "----------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(uri);
webrequest.CookieContainer = cookies;
webrequest.ContentType = "multipart/form-data; boundary=" + boundary;
webrequest.Method = "POST";
// Build up the post message header
StringBuilder sb = new StringBuilder();
sb.Append("--");
sb.Append(boundary);
sb.Append("");
sb.Append("Content-Disposition: form-data; name=\"");
sb.Append(fileFormName);
sb.Append("\"; filename=\"");
sb.Append(Path.GetFileName(uploadfile));
sb.Append("\"");
sb.Append("");
sb.Append("Content-Type: ");
sb.Append(contenttype);
sb.Append("");
sb.Append("");
string postHeader = sb.ToString();
byte[] postHeaderBytes = Encoding.UTF8.GetBytes(postHeader);
// Build the trailing boundary string as a byte array
// ensuring the boundary appears on a line by itself
byte[] boundaryBytes =
Encoding.ASCII.GetBytes("--" + boundary + "");
FileStream fileStream = new FileStream(uploadfile,
FileMode.Open, FileAccess.Read);
long length = postHeaderBytes.Length + fileStream.Length +
boundaryBytes.Length;
webrequest.ContentLength = length;
Stream requestStream = webrequest.GetRequestStream();
// Write out our post header
requestStream.Write(postHeaderBytes, 0, postHeaderBytes.Length);
// Write out the file contents
byte[] buffer = new Byte[checked((uint)Math.Min(4096,
(int)fileStream.Length))];
int bytesRead = 0;
while ( (bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0 )
requestStream.Write(buffer, 0, bytesRead);
// Write out the trailing boundary
requestStream.Write(boundaryBytes, 0, boundaryBytes.Length);
WebResponse responce = webrequest.GetResponse();
Stream s = responce.GetResponseStream();
StreamReader sr = new StreamReader(s);
return sr.ReadToEnd();
}
调用代码如下:
CookieContainer cookies = new CookieContainer();
//add or use cookies
NameValueCollection querystring = new NameValueCollection();
querystring["uname"]="uname";
querystring["passwd"]="snake3";
string uploadfile;// set to file to upload
uploadfile = "c:\\test.jpg";
//everything except upload file and url can be left blank if needed
string outdata = UploadFileEx(uploadfile,
"http://localhost/test.php","uploadfile", "image/pjpeg",
querystring,cookies);
至此,所有主要功能代码都已经介绍完毕,至于美化你的程序就要读者根据自己的喜好完成了。
作者还提供了接收文件的PHP代码,,个人觉得既然能写上传的程序,接收文件的Server Page应该不在话下的,况且又不是PHP才能接收提交的文件,ASP,ASP.NET,JSP都可以,这里就不再啰嗦了。
0
投稿
猜你喜欢
- 一,背景之所以会想到一个服务同时使用eureka和nacos,是因为遇到一个需求,配置数据是存储在nacos的配置中,然后使用该配置的服务却
- 简介说明本文用实例来介绍@Autowired解决循环依赖的原理。@Autowired是通过 * 缓存来解决循环依赖的。 除了@Aut
- 首先引入pom <!--SpringBoot 2.1.0--> <parent>  
- 线程池主要解决两个问题:一是当执行大量异步任务时线程池能够提供较好的性能。在不使用线程池时,每当需要执行异步任务时直接new一个线程来运行,
- 接着上次的实现, 添加 mybatis 查询 orcale 数据库第一步: 新建几个必须的包, 结果如下第二步: 在service包下新建p
- 算法描述堆排序算法的描述如下:将待排序的数组调整为最大堆,此时未排序的长度 N 为数组的长度,调整的过程就是倒序将数组的
- 本文实例讲述了Java实现的zip工具类。分享给大家供大家参考,具体如下:实现把zip解压到指定路径,把文件夹压缩到zip,把文件列表压缩为
- 这里来讲一下后台java如何构造多叉树,这样前台就可接收到数据递归构造树形菜单了。我们来理一下如何实现构造多叉树的逻辑吧,其实整个问题概括起
- 一、定界符成帧Framer接口package framer;import java.io.IOException;import java.i
- 一般文本文件我们以日志文件.log文件为例:import java.io.BufferedReader; import java.io.Fi
- 综述在Android系统中,出于对性能优化的考虑,对于Android的UI操作并不是线程安全的。也就是说若是有多个线程来操作UI组件,就会有
- 我这里有一个需求需要修改Person类中的一个属性上的注解的值进行修改,例如:public class Person { private i
- Spring Boot中可以在配置文件中直接进行数据库配置,spring.datasource.username= rootspring.d
- 前言Java项目开发中经常要用到分页功能,现在普遍使用SpringBoot进行快速开发,而数据层主要整合SpringDataJPA和MyBa
- 枚举的定义1.题目枚举是JAVA 5.0后增加的一个重要类型。可以用来表示一组取值范围固定的变量。使用enum关键字,可以定义枚举类型。实现
- 前段时间接到一个Web应用自动生成Word的需求,现整理了下一些关键步骤拿来分享一下。思路:(注:这里只针对WORD2003版本,其它版本大
- springboot项目启动的时候参数无效今天启动一个springboot项目发现启动的时候输入的参数都是不能生效,但是yaml文件的配置却
- 前言SpringBoot是我们经常使用的框架,那么你能不能针对SpringBoot实现自动配置做一个详细的介绍。如果可以的话,能不能画一下实
- 本文实例讲述了C#实现简单合并word文档的方法。分享给大家供大家参考。具体如下:using System;using System.Col
- 在前面的文章<Mybatis配置之<properties>属性配置元素详述>,我们讲述了<properties