1、关于webclient第三方的封装,支持多文件上传等
using system;
using system.collections.generic;
using system.text;
using system.net;
using system.net.sockets;
using system.collections;
using system.io;
using system.text.regularexpressions;
using re = system.text.regularexpressions.regex;
using system.security.cryptography.x509certificates;
/***************************************************************************************************************************************************
* *文件名:httpproc.cs
* *创建人:kenter
* *日 期:2010.02.23 修改
* *描 述:实现http协议中的get、post请求
* *使 用:httpproc.webclient client = new httpproc.webclient();
client.encoding = system.text.encoding.default;//默认编码方式,根据需要设置其他类型
client.openread("http://www.baidu.com");//普通get请求
messagebox.show(client.resphtml);//获取返回的网页源代码
client.downloadfile("http://www.codepub.com/upload/163album.rar",@"c:163album.rar");//下载文件
client.openread("http://passport.baidu.com/?login","username=zhangsan&password=123456");//提交表单,此处是登录百度的示例
client.uploadfile("http://hiup.baidu.com/zhangsan/upload", @"file1=d:1.mp3");//上传文件
client.uploadfile("http://hiup.baidu.com/zhangsan/upload", "folder=myfolder&size=4003550",@"file1=d:1.mp3");//提交含文本域和文件域的表单
*****************************************************************************************************************************************************/
namespace httpproc
{
///<summary>
///上传事件委托
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
public delegate void webclientuploadevent(object sender, httpproc.uploadeventargs e);
///<summary>
///下载事件委托
///</summary>
///<param name="sender"></param>
///<param name="e"></param>
public delegate void webclientdownloadevent(object sender, httpproc.downloadeventargs e);
///<summary>
///上传事件参数
///</summary>
public struct uploadeventargs
{
///<summary>
///上传数据总大小
///</summary>
public long totalbytes;
///<summary>
///已发数据大小
///</summary>
public long bytessent;
///<summary>
///发送进度(0-1)
///</summary>
public double sendprogress;
///<summary>
///发送速度bytes/s
///</summary>
public double sendspeed;
}
///<summary>
///下载事件参数
///</summary>
public struct downloadeventargs
{
///<summary>
///下载数据总大小
///</summary>
public long totalbytes;
///<summary>
///已接收数据大小
///</summary>
public long bytesreceived;
///<summary>
///接收数据进度(0-1)
///</summary>
public double receiveprogress;
///<summary>
///当前缓冲区数据
///</summary>
public byte[] receivedbuffer;
///<summary>
///接收速度bytes/s
///</summary>
public double receivespeed;
}
///<summary>
///实现向web服务器发送和接收数据
///</summary>
public class webclient
{
private webheadercollection requestheaders, responseheaders;
private tcpclient clientsocket;
private memorystream poststream;
private encoding encoding = encoding.default;
private const string boundary = "--hedaode--";
private const int send_buffer_size = 10245;
private const int receive_buffer_size = 10245;
private string cookie = "";
private string resphtml = "";
private string strrequestheaders = "";
private string strresponseheaders = "";
private int statuscode = 0;
private bool iscanceled = false;
public event webclientuploadevent uploadprogresschanged;
public event webclientdownloadevent downloadprogresschanged;
///<summary>
///初始化webclient类
///</summary>
public webclient()
{
responseheaders = new webheadercollection();
requestheaders = new webheadercollection();
}
/// <summary>
/// 获得字符串中开始和结束字符串中间得值
/// </summary>
/// <param name="str"></param>
/// <param name="s">开始</param>
/// <param name="e">结束</param>
/// <returns></returns>
public string gethtmlcontent(string str, string s, string e)
{
regex rg = new regex("(?<=(" + s + "))[.ss]*?(?=(" + e + "))", regexoptions.multiline | regexoptions.singleline);
return rg.match(str).value;
}
/// <summary>
/// 过滤html字符
/// </summary>
/// <param name="source"></param>
/// <returns></returns>
public string htmlconvert(string source)
{
string result;
//remove line breaks,tabs
result = source.replace("r", " ");
result = result.replace("n", " ");
result = result.replace("t", " ");
//remove the header
result = regex.replace(result, "(<head>).*(</head>)", string.empty, regexoptions.ignorecase);
result = regex.replace(result, @"<( )*script([^>])*>", "<script>", regexoptions.ignorecase);
result = regex.replace(result, @"(<script>).*(</script>)", string.empty, regexoptions.ignorecase);
//remove all styles
result = regex.replace(result, @"<( )*style([^>])*>", "<style>", regexoptions.ignorecase); //clearing attributes
result = regex.replace(result, "(<style>).*(</style>)", string.empty, regexoptions.ignorecase);
//insert tabs in spaces of <td> tags
result = regex.replace(result, @"<( )*td([^>])*>", " ", regexoptions.ignorecase);
//insert line breaks in places of <br> and <li> tags
result = regex.replace(result, @"<( )*br( )*>", "r", regexoptions.ignorecase);
result = regex.replace(result, @"<( )*li( )*>", "r", regexoptions.ignorecase);
//insert line paragraphs in places of <tr> and <p> tags
result = regex.replace(result, @"<( )*tr([^>])*>", "rr", regexoptions.ignorecase);
result = regex.replace(result, @"<( )*p([^>])*>", "rr", regexoptions.ignorecase);
//remove anything thats enclosed inside < >
result = regex.replace(result, @"<[^>]*>", string.empty, regexoptions.ignorecase);
//replace special characters:
result = regex.replace(result, @"&", "&", regexoptions.ignorecase);
result = regex.replace(result, @" ", " ", regexoptions.ignorecase);
result = regex.replace(result, @"<", "<", regexoptions.ignorecase);
result = regex.replace(result, @">", ">", regexoptions.ignorecase);
result = regex.replace(result, @"&(.{2,6});", string.empty, regexoptions.ignorecase);
//remove extra line breaks and tabs
result = regex.replace(result, @" ( )+", " ");
result = regex.replace(result, "(r)( )+(r)", "rr");
result = regex.replace(result, @"(rr)+", "rn");
return result;
}
///<summary>
///读取指定url的文本
///</summary>
///<param name="url">请求的地址</param>
///<returns>服务器响应文本</returns>
public string openread(string url)
{
requestheaders.add("connection", "close");
sendrequestdata(url, "get");
return gethtml();
}
//解决证书过期无法访问的问题
class certpolicy : icertificatepolicy
{
public bool checkvalidationresult(servicepoint srvpt, x509certificate cert, webrequest req, int certprb)
{ return true; }
}
///<summary>
///采用https协议访问网络
///</summary>
///<param name="url">url地址</param>
///<param name="strpostdata">发送的数据</param>
///<returns></returns>
public string openreadwithhttps(string url, string strpostdata)
{
servicepointmanager.certificatepolicy = new certpolicy();
httpwebrequest request = (httpwebrequest)webrequest.create(url);
request.cookiecontainer = new cookiecontainer();
request.method = "post";
request.accept = "*/*";
request.contenttype = "application/x-www-form-urlencoded";
byte[] buffer = this.encoding.getbytes(strpostdata);
request.contentlength = buffer.length;
request.getrequeststream().write(buffer, 0, buffer.length);
httpwebresponse response = (httpwebresponse)request.getresponse();
streamreader reader = new streamreader(response.getresponsestream(), encoding);
this.resphtml = reader.readtoend();
foreach (system.net.cookie ck in response.cookies)
{
this.cookie += ck.name + "=" + ck.value + ";";
}
reader.close();
return resphtml;
}
///<summary>
///读取指定url的文本
///</summary>
///<param name="url">请求的地址</param>
///<param name="postdata">向服务器发送的文本数据</param>
///<returns>服务器响应文本</returns>
public string openread(string url, string postdata)
{
byte[] sendbytes = encoding.getbytes(postdata);
poststream = new memorystream();
poststream.write(sendbytes, 0, sendbytes.length);
requestheaders.add("content-length", poststream.length.tostring());
requestheaders.add("content-type", "application/x-www-form-urlencoded");
requestheaders.add("connection", "close");
sendrequestdata(url, "post");
return gethtml();
}
///<summary>
///读取指定url的流
///</summary>
///<param name="url">请求的地址</param>
///<param name="postdata">向服务器发送的数据</param>
///<returns>服务器响应流</returns>
public stream getstream(string url, string postdata)
{
byte[] sendbytes = encoding.getbytes(postdata);
poststream = new memorystream();
poststream.write(sendbytes, 0, sendbytes.length);
requestheaders.add("content-length", poststream.length.tostring());
requestheaders.add("content-type", "application/x-www-form-urlencoded");
requestheaders.add("connection", "close");
sendrequestdata(url, "post");
memorystream ms = new memorystream();
savenetworkstream(ms);
return ms;
}
///<summary>
///上传文件到服务器
///</summary>
///<param name="url">请求的地址</param>
///<param name="filefield">文件域(格式如:file1=c:test.mp3&file2=c:test.jpg)</param>
///<returns>服务器响应文本</returns>
public string uploadfile(string url, string filefield)
{
return uploadfile(url, "", filefield);
}
///<summary>
///上传文件和数据到服务器
///</summary>
///<param name="url">请求地址</param>
///<param name="textfield">文本域(格式为:name1=value1&name2=value2)</param>
///<param name="filefield">文件域(格式如:file1=c:test.mp3&file2=c:test.jpg)</param>
///<returns>服务器响应文本</returns>
public string uploadfile(string url, string textfield, string filefield)
{
poststream = new memorystream();
if (textfield != "" && filefield != "")
{
writetextfield(textfield);
writefilefield(filefield);
}
else if (filefield != "")
{
writefilefield(filefield);
}
else if (textfield != "")
{
writetextfield(textfield);
}
else
throw new exception("文本域和文件域不能同时为空。");
//写入结束标记
byte[] buffer = encoding.getbytes("--" + boundary + "--rn");
poststream.write(buffer, 0, buffer.length);
//添加请求标头
requestheaders.add("content-length", poststream.length.tostring());
requestheaders.add("content-type", "multipart/form-data; boundary=" + boundary);
requestheaders.add("connection", "keep-alive");
//发送请求数据
sendrequestdata(url, "post", true);
//返回响应文本
return gethtml();
}
///<summary>
///分析文本域,添加到请求流
///</summary>
///<param name="textfield">文本域</param>
private void writetextfield(string textfield)
{
string[] strarr = re.split(textfield, "&");
textfield = "";
foreach (string var in strarr)
{
match m = re.match(var, "([^=]+)=(.+)");
textfield += "--" + boundary + "rn";
textfield += "content-disposition: form-data; name="" + m.groups[1].value + ""rnrn" + m.groups[2].value + "rn";
}
byte[] buffer = encoding.getbytes(textfield);
poststream.write(buffer, 0, buffer.length);
}
///<summary>
///分析文件域,添加到请求流
///</summary>
///<param name="filefield">文件域</param>
private void writefilefield(string filefield)
{
string filepath = "";
int count = 0;
string[] strarr = re.split(filefield, "&");
foreach (string var in strarr)
{
match m = re.match(var, "([^=]+)=(.+)");
filepath = m.groups[2].value;
filefield = "--" + boundary + "rn";
filefield += "content-disposition: form-data; name="" + m.groups[1].value + ""; filename="" + path.getfilename(filepath) + ""rn";
filefield += "content-type: image/jpegrnrn";
byte[] buffer = encoding.getbytes(filefield);
poststream.write(buffer, 0, buffer.length);
//添加文件数据
filestream fs = new filestream(filepath, filemode.open, fileaccess.read);
buffer = new byte[50000];
do
{
count = fs.read(buffer, 0, buffer.length);
poststream.write(buffer, 0, count);
} while (count > 0);
fs.close();
fs.dispose();
fs = null;
buffer = encoding.getbytes("rn");
poststream.write(buffer, 0, buffer.length);
}
}
///<summary>
///从指定url下载数据流
///</summary>
///<param name="url">请求地址</param>
///<returns>数据流</returns>
public stream downloaddata(string url)
{
requestheaders.add("connection", "close");
sendrequestdata(url, "get");
memorystream ms = new memorystream();
savenetworkstream(ms, true);
return ms;
}
///<summary>
///从指定url下载文件
///</summary>
///<param name="url">文件url地址</param>
///<param name="filename">文件保存路径,含文件名(如:c:test.jpg)</param>
public void downloadfile(string url, string filename)
{
requestheaders.add("connection", "close");
sendrequestdata(url, "get");
filestream fs = new filestream(filename, filemode.create);
savenetworkstream(fs, true);
fs.close();
fs = null;
}
///<summary>
///向服务器发送请求
///</summary>
///<param name="url">请求地址</param>
///<param name="method">post或get</param>
///<param name="showprogress">是否显示上传进度</param>
private void sendrequestdata(string url, string method, bool showprogress)
{
clientsocket = new tcpclient();
uri uri = new uri(url);
clientsocket.connect(uri.host, uri.port);
requestheaders.add("host", uri.host);
byte[] request = getrequestheaders(method + " " + uri.pathandquery + " http/1.1");
clientsocket.client.send(request);
//若有实体内容就发送它
if (poststream != null)
{
byte[] buffer = new byte[send_buffer_size];
int count = 0;
stream sm = clientsocket.getstream();
poststream.position = 0;
uploadeventargs e = new uploadeventargs();
e.totalbytes = poststream.length;
system.diagnostics.stopwatch timer = new system.diagnostics.stopwatch();//计时器
timer.start();
do
{
//如果取消就推出
if (iscanceled) { break; }
//读取要发送的数据
count = poststream.read(buffer, 0, buffer.length);
//发送到服务器
sm.write(buffer, 0, count);
//是否显示进度
if (showprogress)
{
//触发事件
e.bytessent += count;
e.sendprogress = (double)e.bytessent / (double)e.totalbytes;
double t = timer.elapsedmilliseconds / 1000;
t = t <= 0 ? 1 : t;
e.sendspeed = (double)e.bytessent / t;
if (uploadprogresschanged != null) { uploadprogresschanged(this, e); }
}
} while (count > 0);
timer.stop();
poststream.close();
//poststream.dispose();
poststream = null;
}//end if
}
///<summary>
///向服务器发送请求
///</summary>
///<param name="url">请求url地址</param>
///<param name="method">post或get</param>
private void sendrequestdata(string url, string method)
{
sendrequestdata(url, method, false);
}
///<summary>
///获取请求头字节数组
///</summary>
///<param name="request">post或get请求</param>
///<returns>请求头字节数组</returns>
private byte[] getrequestheaders(string request)
{
requestheaders.add("accept", "*/*");
requestheaders.add("accept-language", "zh-cn");
requestheaders.add("user-agent", "mozilla/4.0 (compatible; msie 6.0; windows nt 5.2; sv1; .net clr 1.1.4322; .net clr 2.0.50727)");
string headers = request + "rn";
foreach (string key in requestheaders)
{
headers += key + ":" + requestheaders[key] + "rn";
}
//有cookie就带上cookie
if (cookie != "") { headers += "cookie:" + cookie + "rn"; }
//空行,请求头结束
headers += "rn";
strrequestheaders = headers;
requestheaders.clear();
return encoding.getbytes(headers);
}
///<summary>
///获取服务器响应文本
///</summary>
///<returns>服务器响应文本</returns>
private string gethtml()
{
memorystream ms = new memorystream();
savenetworkstream(ms);//将网络流保存到内存流
streamreader sr = new streamreader(ms, encoding);
resphtml = sr.readtoend();
sr.close(); ms.close();
return resphtml;
}
///<summary>
///将网络流保存到指定流
///</summary>
///<param name="tostream">保存位置</param>
///<param name="needprogress">是否显示进度</param>
private void savenetworkstream(stream tostream, bool showprogress)
{
//获取要保存的网络流
networkstream netstream = clientsocket.getstream();
byte[] buffer = new byte[receive_buffer_size];
int count = 0, startindex = 0;
memorystream ms = new memorystream();
for (int i = 0; i < 3; i++)
{
count = netstream.read(buffer, 0, 500);
ms.write(buffer, 0, count);
}
if (ms.length == 0) { netstream.close(); throw new exception("远程服务器没有响应"); }
buffer = ms.getbuffer();
count = (int)ms.length;
getresponseheader(buffer, out startindex);//分析响应,获取响应头和响应实体
count -= startindex;
tostream.write(buffer, startindex, count);
downloadeventargs e = new downloadeventargs();
if (responseheaders["content-length"] != null)
{ e.totalbytes = long.parse(responseheaders["content-length"]); }
else
{ e.totalbytes = -1; }
//启动计时器
system.diagnostics.stopwatch timer = new system.diagnostics.stopwatch();
timer.start();
do
{
//如果取消就推出
if (iscanceled) { break; }
//显示下载进度
if (showprogress)
{
e.bytesreceived += count;
e.receiveprogress = (double)e.bytesreceived / (double)e.totalbytes;
byte[] tempbuffer = new byte[count];
array.copy(buffer, startindex, tempbuffer, 0, count);
e.receivedbuffer = tempbuffer;
double t = (timer.elapsedmilliseconds + 0.1) / 1000;
e.receivespeed = (double)e.bytesreceived / t;
startindex = 0;
if (downloadprogresschanged != null) { downloadprogresschanged(this, e); }
}
//读取网路数据到缓冲区
count = netstream.read(buffer, 0, buffer.length);
//将缓存区数据保存到指定流
tostream.write(buffer, 0, count);
} while (count > 0);
timer.stop();//关闭计时器
if (responseheaders["content-length"] != null)
{
tostream.setlength(long.parse(responseheaders["content-length"]));
}
//else
//{
// tostream.setlength(tostream.length);
// responseheaders.add("content-length", tostream.length.tostring());//添加响应标头
//}
tostream.position = 0;
//关闭网络流和网络连接
netstream.close();
clientsocket.close();
}
///<summary>
///将网络流保存到指定流
///</summary>
///<param name="tostream">保存位置</param>
private void savenetworkstream(stream tostream)
{
savenetworkstream(tostream, false);
}
///<summary>
///分析响应流,去掉响应头
///</summary>
///<param name="buffer"></param>
private void getresponseheader(byte[] buffer, out int startindex)
{
responseheaders.clear();
string html = encoding.getstring(buffer);
stringreader sr = new stringreader(html);
int start = html.indexof("rnrn") + 4;//找到空行位置
strresponseheaders = html.substring(0, start);//获取响应头文本
//获取响应状态码
//
if (sr.peek() > -1)
{
//读第一行字符串
string line = sr.readline();
//分析此行字符串,获取服务器响应状态码
match m = re.match(line, @"ddd");
if (m.success)
{
statuscode = int.parse(m.value);
}
}
//获取响应头
//
while (sr.peek() > -1)
{
//读一行字符串
string line = sr.readline();
//若非空行
if (line != "")
{
//分析此行字符串,获取响应标头
match m = re.match(line, "([^:]+):(.+)");
if (m.success)
{
try
{ //添加响应标头到集合
responseheaders.add(m.groups[1].value.trim(), m.groups[2].value.trim());
}
catch
{ }
//获取cookie
if (m.groups[1].value == "set-cookie")
{
m = re.match(m.groups[2].value, "[^=]+=[^;]+");
cookie += m.value.trim() + ";";
}
}
}
//若是空行,代表响应头结束响应实体开始。(响应头和响应实体间用一空行隔开)
else
{
//如果响应头中没有实体大小标头,尝试读响应实体第一行获取实体大小
if (responseheaders["content-length"] == null && sr.peek() > -1)
{
//读响应实体第一行
line = sr.readline();
//分析此行看是否包含实体大小
match m = re.match(line, "~[0-9a-fa-f]{1,15}");
if (m.success)
{
//将16进制的实体大小字符串转换为10进制
int length = int.parse(m.value, system.globalization.numberstyles.allowhexspecifier);
responseheaders.add("content-length", length.tostring());//添加响应标头
strresponseheaders += m.value + "rn";
}
}
break;//跳出循环
}//end if
}//end while
sr.close();
//实体开始索引
startindex = encoding.getbytes(strresponseheaders).length;
}
///<summary>
///取消上传或下载,要继续开始请调用start方法
///</summary>
public void cancel()
{
iscanceled = true;
}
///<summary>
///启动上传或下载,要取消请调用cancel方法
///</summary>
public void start()
{
iscanceled = false;
}
//*************************************************************
//以下为属性
//*************************************************************
///<summary>
///获取或设置请求头
///</summary>
public webheadercollection requestheaders
{
set { requestheaders = value; }
get { return requestheaders; }
}
///<summary>
///获取响应头集合
///</summary>
public webheadercollection responseheaders
{
get { return responseheaders; }
}
///<summary>
///获取请求头文本
///</summary>
public string strrequestheaders
{
get { return strrequestheaders; }
}
///<summary>
///获取响应头文本
///</summary>
public string strresponseheaders
{
get { return strresponseheaders; }
}
///<summary>
///获取或设置cookie
///</summary>
public string cookie
{
set { cookie = value; }
get { return cookie; }
}
///<summary>
///获取或设置编码方式(默认为系统默认编码方式)
///</summary>
public encoding encoding
{
set { encoding = value; }
get { return encoding; }
}
///<summary>
///获取服务器响应文本
///</summary>
public string resphtml
{
get { return resphtml; }
}
///<summary>
///获取服务器响应状态码
///</summary>
public int statuscode
{
get { return statuscode; }
}
}
}
2、webrequest实现多文件文件上载
封装类:
public class uploadfile
{
public uploadfile()
{
contenttype = "application/octet-stream";
}
public string name { get; set; }
public string filename { get; set; }
public string contenttype { get; set; }
public stream stream { get; set; }
}
class classtest
{
public byte[] uploadfiles(string address, ienumerable<uploadfile> files, namevaluecollection values)
{
var request = webrequest.create(address);
request.method = "post";
var boundary = "---------------------------" + datetime.now.ticks.tostring("x", numberformatinfo.invariantinfo);
request.contenttype = "multipart/form-data; boundary=" + boundary;
boundary = "--" + boundary;
using (var requeststream = request.getrequeststream())
{
// write the values
foreach (string name in values.keys)
{
var buffer = encoding.ascii.getbytes(boundary + environment.newline);
requeststream.write(buffer, 0, buffer.length);
buffer = encoding.ascii.getbytes(string.format("content-disposition: form-data; name="{0}"{1}{1}", name, environment.newline));
requeststream.write(buffer, 0, buffer.length);
buffer = encoding.utf8.getbytes(values[name] + environment.newline);
requeststream.write(buffer, 0, buffer.length);
}
// write the files
foreach (var file in files)
{
var buffer = encoding.ascii.getbytes(boundary + environment.newline);
requeststream.write(buffer, 0, buffer.length);
buffer = encoding.utf8.getbytes(string.format("content-disposition: form-data; name="{0}"; filename="{1}"{2}", file.name, file.filename, environment.newline));
requeststream.write(buffer, 0, buffer.length);
buffer = encoding.ascii.getbytes(string.format("content-type: {0}{1}{1}", file.contenttype, environment.newline));
requeststream.write(buffer, 0, buffer.length);
file.stream.copyto(requeststream);
buffer = encoding.ascii.getbytes(environment.newline);
requeststream.write(buffer, 0, buffer.length);
}
var boundarybuffer = encoding.ascii.getbytes(boundary + "--");
requeststream.write(boundarybuffer, 0, boundarybuffer.length);
}
using (var response = request.getresponse())
using (var responsestream = response.getresponsestream())
using (var stream = new memorystream())
{
responsestream.copyto(stream);
return stream.toarray();
}
}
}
使用:
using (var stream1 = file.open("test.txt", filemode.open))
using (var stream2 = file.open("test.xml", filemode.open))
using (var stream3 = file.open("test.pdf", filemode.open))
{
var files = new[]
{
new uploadfile
{
name = "file",
filename = "test.txt",
contenttype = "text/plain",
stream = stream1
},
new uploadfile
{
name = "file",
filename = "test.xml",
contenttype = "text/xml",
stream = stream2
},
new uploadfile
{
name = "file",
filename = "test.pdf",
contenttype = "application/pdf",
stream = stream3
}
};
var values = new namevaluecollection
{
{ "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" },
};
byte[] result = uploadfiles("http://localhost:1234/upload", files, values);
}
3、下面httpwebrequestt
c#采用httpwebrequest实现保持会话上传文件到http的方法
我们使用 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);
【说明】:本文章由站长整理发布,文章内容不代表本站观点,如文中有侵权行为,请与本站客服联系(QQ:254677821)!