使用WebClient Post方式模拟上传文件和数据
假如某网站有个表单,例如(url: http://localhost/login.aspx):
帐号
密码
我们需要在程序中提交数据到这个表单,对于这种表单,我们可以使用 WebClient.UploadData 方法来实现,将所要上传的
数据拼成字符即可,程序很简单
对于文件上传类的表单,例如(url: http://localhost/uploadFile.aspx):
文件
对于这种表单,我们可以使用
// 创建一个新的 WebClient 实例.WebClient myWebClient = new WebClient();
string fileName = @"C:\upload.txt";
// 直接上传,并获取返回的二进制数据.byte[] responseArray = myWebClient.UploadFile(uriString, "POST", fileName);
还有一种表单,不仅有文字,还有文件,例如(url: http://localhost/uploadData.aspx):
文件名
文件
对于这种表单,似乎前面的两种方法都不能适用,对于第一种方法,不能直接拼字符串,对于第二种,我们只能传文件,重新回到第一个方法,注意参数:
public byte[] UploadData(
string address,
string method,
byte[] data
);
在第一个例子中,是通过拼字符串来得到byte[] data参数值的,对于这种表单显然不行,反过来想想,对于uploadData.aspx这样的程序来说,直接通过网页提交数据,后台所获取到的流是什么样的呢 ,最终的数据如下:
-----------------------------7d429871607fe
Content-Disposition: form-data; name="file1"; filename="G:\homepage.txt"
Content-Type: text/plain
宝玉:http://www.webuc.net
-----------------------------7d429871607fe
Content-Disposition: form-data; name="filename"
default filename
-----------------------------7d429871607fe--
所以只要拼一个这样的byte[] data数据Post过去,就可以达到同样的效果了。但是一定要注意,对于这种带有文件上传的,其ContentType是不一样的,例如上面的这种,其ContentType为"multipart/form-data; boundary=---------------------------7d429871607fe"。有了ContentType,我们就可以知道boundary(就是上面的"---------------------------7d429871607fe"),知道boundary了我们就可以构造出我们所需要的byte[] data了,最后,不要忘记,把我们构造的ContentType传到WebClient中(例如:webClient.Headers.Add("Content-Type", ContentType);)这样,就可以通过WebClient.UploadData 方法上载文件数据了。
具体代码如下:生成二进制数据类的封装
/**//// <summary> /// 拼接所有的二进制数组为一个数组/// </summary> /// <param name="byteArrays">数组</param>
/// <returns></returns>
/// <remarks>加上结束边界</remarks>public byte[] JoinBytes(ArrayList byteArrays)
{
int length = 0;int readLength = 0;
// 加上结束边界string endBoundary = Boundary + "--\r\n"; //结束边界byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
byteArrays.Add(endBoundaryBytes);
foreach(byte[] b in byteArrays)
{
length += b.Length;
}
byte[] bytes = new byte[length];
// 遍历复制
//
foreach(byte[] b in byteArrays)
{
b.CopyTo(bytes, readLength);
readLength += b.Length;
}
return bytes;
}
public bool UploadData(string uploadUrl, byte[] bytes, out byte[] responseBytes)
{
WebClient webClient = new WebClient(); webClient.Headers.Add("Content-Type", ContentType);
try{
responseBytes = webClient.UploadData(uploadUrl, bytes);
return true;
}
catch (WebException ex)
{
Stream resp = ex.Response.GetResponseStream(); responseBytes = new byte[ex.Response.ContentLength];
resp.Read(responseBytes, 0, responseBytes.Length);
}
return false;
}
/**//// <summary> /// 获取普通表单区域二进制数组/// </summary> /// <param name="fieldName">表单名</param> /// <param name="fieldValue">表单值</param>
/// <returns></returns>
/// <remarks>
/// -----------------------------7d52ee27210a3c\r\nContent-Disposition: form-data; name=\"表单名\"\r\n\r\n表单值\r\n/// </remarks>public byte[] CreateFieldData(string fieldName, string fieldValue)
{
string textTemplate = Boundary + "\r\nContent-Disposition: form-data; name=\"{0}\"\r\n\r\n{1}\r\n";string text = String.Format(textTemplate, fieldName, fieldValue);byte[] bytes = encoding.GetBytes(text);return bytes;
}
/**//// <summary> /// 获取文件上传表单区域二进制数组/// </summary> /// <param name="fieldName">表单名</param> /// <param name="filename">文件名</param> /// <param name="contentType">文件类型</param> /// <param name="contentLength">文件长度</param> /// <param name="stream">文件流</param> /// <returns>二进制数组</returns>public byte[] CreateFieldData(string fieldName, string filename,string contentType, byte[] fileBytes)
{
string end = "\r\n";string textTemplate = Boundary + "\r\n Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\nContent-Type: {2}\r\n\r\n";
// 头数据string data = String.Format(textTemplate, fieldName, filename, contentType);byte[] bytes = encoding.GetBytes(data);
// 尾数据byte[] endBytes = encoding.GetBytes(end);
// 合成后的数组byte[] fieldData = new byte[bytes.Length + fileBytes.Length + endBytes.Length];
bytes.CopyTo(fieldData, 0); // 头数据fileBytes.CopyTo(fieldData, bytes.Length); // 文件的二进制数据endBytes.CopyTo(fieldData, bytes.Length + fileBytes.Length); // \r\n
return fieldData;
}
// 属性#region 属性public string Boundary
{
get {string[] bArray, ctArray;string contentType = ContentType; ctArray = contentType.Split(';');if (ctArray[0].Trim().ToLower() == "multipart/form-data")
{
bArray = ctArray[1].Split('=');return "--" + bArray[1];
}
return null;
}
}
public string ContentType
{
get {//if (HttpContext.Current == null)
//{
return "multipart/form-data; boundary=---------------------------7d5b915500cee";//}
//return HttpContext.Current.Request.ContentType;
}
}
#endregion}
在Winform中调用
{
//// 非空检验
//if (txtAmigoToken.Text.Trim() == "" || txtFilename.Text == "" || txtFileData.Text.Trim() == "")
//{
// MessageBox.Show("Please fill data");
// return;
//}
// 所要上传的文件路径
string fileFullName="c:/aa.txt";string path = fileFullName; //txtFileData.Text.Trim();
// 检查文件是否存在
if (!File.Exists(path))
{
MessageBox.Show("{0} does not exist!", path);return;
}
// 读文件流FileStream fs = new FileStream(path, FileMode.Open,FileAccess.Read, FileShare.Read);
// 这部分需要完善string ContentType = "application/octet-stream";byte[] fileBytes = new byte[fs.Length]; fs.Read(fileBytes, 0, Convert.ToInt32(fs.Length));
// 生成需要上传的二进制数组CreateBytes cb = new CreateBytes();// 所有表单数据ArrayList bytesArray = new ArrayList();// 普通表单bytesArray.Add(cb.CreateFieldData("subdir", "uploadFiles"));//bytesArray.Add(cb.CreateFieldData("AmigoToken", txtAmigoToken.Text));
// 文件表单
bytesArray.Add(cb.CreateFieldData("FileData", path
, ContentType, fileBytes));
// 合成所有表单并生成二进制数组byte[] bytes = cb.JoinBytes(bytesArray);
// 返回的内容byte[] responseBytes;
// 上传到指定Urlbool uploaded = cb.UploadData("http://localhost/UploadData/UploadAvatar.aspx", bytes, out responseBytes);string retStr = System.Text.Encoding.UTF8.GetString(responseBytes);// 将返回的内容输出到文件
//using (FileStream file = new FileStream(@"c:\response.text", FileMode.Create, FileAccess.Write, FileShare.Read))
//{
// file.Write(responseBytes, 0, responseBytes.Length);
//}
// txtResponse.Text = System.Text.Encoding.UTF8.GetString(responseBytes);
}
使用WebClient Post方式模拟上传文件和数据的更多相关文章
- WebAPI通过multipart/form-data方式同时上传文件以及数据(含HttpClient上传Demo)
简单的Demo,用于了解WebAPI如何同时接收文件及数据,同时提供HttpClient模拟如何同时上传文件和数据的Demo,下面是HttpClient上传的Demo界面 1.HttpClient部分 ...
- 【转】asp.net(c#)使用HttpWebRequest附加携带请求参数以post方式模拟上传大文件(以图片为例)到Web服务器端
原文地址:http://docode.top/Article/Detail/10002 目录: 1.Http协议上传文件(以图片为例)请求报文体内容格式 2.完整版HttpWebRequest模拟上传 ...
- java 模拟表单方式提交上传文件
/** * 模拟form表单的形式 ,上传文件 以输出流的形式把文件写入到url中,然后用输入流来获取url的响应 * * @param url 请求地址 form表单url地址 * @param f ...
- 一个Jmeter模拟上传文件接口的实例
资料参考:https://blog.csdn.net/u010390063/article/details/78329373 项目中,避免不了要用到很多上传文件.图片的接口,那么碰到这类接口该如何进行 ...
- linux 软连接方式实现上传文件存储目录的无缝迁移
背景: 由于前期的磁盘空间规划与后期的业务要求不符合.原先/home被用于用户上传文件的存储目录,但是由于上传文件的逐渐增多,而原来的/home目录的空间不足,需要给/home目录进行扩容.同时各个应 ...
- C# WebClient进行FTP服务上传文件和下载文件
定义WebClient使用的操作类: 操作类名称WebUpDown WebClient上传文件至Ftp服务: //// <summary> /// WebClient上传文件至Ftp服务 ...
- Html标签,file方式,上传文件
恩,如果不记下来,记忆就会模糊掉. 希望自己下次看见这篇博客的时候,会解决掉疑问 ----------------------------------------------------------- ...
- vc libcurl 模拟上传文件
http://www.cnblogs.com/killbit/p/5393301.html 附上这篇文章,因为当时就已经想到了模拟上传,但是因为时间关系,所以就直接用PHP写了.现在改进一下,用VC+ ...
- c# 模拟表单提交,post form 上传文件、数据内容
转自:https://www.cnblogs.com/DoNetCShap/p/10696277.html 表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipar ...
随机推荐
- listview去掉底部多出的边框黑色
listview去掉底部多出的边框黑色 android:fadingEdge="none" //去掉listview黑色底边 listview.setDivider(null);
- 猫都能学会的Unity3D Shader入门指南
https://onevcat.com/2013/07/shader-tutorial-1/ https://onevcat.com/2013/08/shader-tutorial-2/
- redis.conf详解
# Redis示例配置文件 # 注意单位问题:当需要设置内存大小的时候,可以使用类似1k.5GB.4M这样的常见格式: # # 1k => bytes # 1kb => bytes # 1 ...
- Spring3.1新特性
一.Spring2.5之前,我们都是通过实现Controller接口或其实现来定义我们的处理器类. 二.Spring2.5引入注解式处理器支持,通过@Controller 和 @RequestMa ...
- .NET Reflector 8.2支持VS2013高亮显示和代码地图视图
Red Gate Software公司最近发布的.NET Reflector 8.2支持Visual Studio 2013,其Reflector 桌面程序能够转换十六进制/十进制值.桌面程序还支持局 ...
- WPF:xmal 静动态资源
<StackPanel.Resources> <SolidColorBrush x:Key="myBrush" Color="Teal"/&g ...
- eclipse 下面的folder,source folder,package的区别与作用
首先明确一点,folder,source folder,package都是文件夹,既然是文件夹,那么任何的文件都可以往这三种文件夹下面的放.1.他们的区别folder就是普通的文件夹,它和我们wind ...
- 在进程View时的四个构造函数详解
public View(Context context):源代码中的解释如下:在Code中实例化一个View就会调用第一个构造函数 /** * Simple constructor to use wh ...
- Java 之 I/O 系列 02 ——序列化(一)
Java 之 I/O 系列 目录 Java 之 I/O 系列 01 ——基础 Java 之 I/O 系列 02 ——序列化(一) Java 之 I/O 系列 02 ——序列化(二) 一 序列化概述 序 ...
- 转载css层级优先级。
解读CSS样式优先级(修改门户自定义样式必读) 一.什么是CSS优先级?所谓CSS优先级,即是指CSS样式在浏览器中被解析的先后顺序.当同一个元素(或内容)被多个CSS选择符选中时,就要按照优先权取舍 ...