2024年5月26日发(作者:)

模拟表单提交数据和上传文件的实现代码

这篇文章主要介绍了

模拟表单提交数据和上传文件的实现代码

,

本文对

3

种情况都做

了介绍

,

只有普通数据的表单、只上传文件的表单、包含普通数据和上传文件表单

,

需要的朋

友可以参考下

如果你需要跨域上传内容到另外一个域名并且需要获取返回值,使用

的作为代理是

最好的办法,要是客户端直接提交到

iframe

中,由于跨域是无法用

javascript

获取到

iframe

中返回的内容的。此时需要在自己的网站做一个动态页作为代理,将表单提交到动态页,动

态页负责将表单的内容使用

WebClient

HttpWebRequest

将表单数据再上传到远程服务器,

由于在服务器端进行操作,就不存在跨域问题了。

WebClient

上传只包含键值对的文本信息示例代码:

复制代码代码如下

:

stringuriString="localhost/";

//

创建一个新的

WebClient

实例

.

WebClientmyWebClient=newWebClient();

stringpostData="Username=admin&Password=admin";

//

注意这种拼字符串的

ContentType

("Content-Type","application/x-www-form-urlencoded");

//

转化成二进制数组

byte[]byteArray=es(postData);

//

上传数据,并获取返回的二进制数据

.

byte[]responseArray=Data(uriString,"POST",byteArray);

WebClient

上传只包含文件的示例代码:

复制代码代码如下

:

StringuriString="localhost/";

//

创建一个新的

WebClient

实例

.

WebClientmyWebClient=newWebClient();

stringfileName=@"C:/";

//

直接上传,并获取返回的二进制数据

.

byte[]responseArray=File(uriString,"POST",fileName);

对于既包含文件又包含文本键值对信息的示例代码,需要构造表单提交的内容,对于学

asp的同学来说,下面的表单提交内容一定不会陌生

复制代码代码如下:

-----------------------------7d429871607fe

Content-Disposition:form-data;name="file1";filename="G:/"

Content-Type:text/plain

-----------------------------7d429871607fe

Content-Disposition:form-data;name="filename"

defaultfilename

-----------------------------7d429871607fe--

所以只要拼一个这样的byte[]data数据Post过去,就可以达到同样的效果了。但是一

定要注意,对于这种带有文件上传的,其ContentType是不一样的,例如上面的这种,其

ContentType为"multipart/form-data;boundary=---------------------------7d429871607fe"。有了

ContentType,我们就可以知道boundary(就是上面的"---------------------------7d429871607fe"),

知道boundary了我们就可以构造出我们所需要的byte[]data了,最后,不要忘记,把我们

构造的ContentType传到WebClient中(例如:("Content-Type",

ContentType);)这样,就可以通过Data方法上载文件数据了。

usingSystem;;;;;using

tions;{publicclassCreateBytes{Encoding

encoding=8;(ArrayListbyteArrays){int

length=0;intreadLength=0;//加上结束边界stringendBoundary=

Boundary+"--";byte[]endBoundaryBytes=es(endBoundary);

(endBoundaryBytes);foreach(byte[]binbyteArrays)

{length+=;}byte[]bytes=newbyte[length];//遍历复

制foreach(byte[]binbyteArrays){(bytes,readLength);

readLength+=;}returnbytes;}publicboolUploadData(string

uploadUrl,byte[]bytes,outbyte[]responseBytes){WebClientwebClient=new

WebClient();("Content-Type",ContentType);try

{responseBytes=Data(uploadUrl,bytes);return

true;}catch(WebExceptionex){Streamresp=

ponseStream();responseBytes=new

byte[tLength];(responseBytes,0,

);}returnfalse;}///获取普通表单区域二进制数

组publicbyte[]CreateFieldData(stringfieldName,stringfieldValue){string