欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

WinForm POST上传与后台接收

程序员文章站 2022-05-17 16:06:31
前端 using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Linq;using System.Tex ......

前端


 

using system;
using system.collections.generic;
using system.componentmodel;
using system.data;
using system.drawing;
using system.linq;
using system.text;
using system.windows.forms;
using system.net;
using system.io;
using system.collections.specialized;

namespace windowsformsapp1
{
public partial class form1 : form
{
webrequest webrequest = webrequest.create("http://localhost/");
public form1()
{
initializecomponent();
}

private void button1_click(object sender, eventargs e)
{
encoding myencoding = encoding.getencoding("utf-8");
//中文参数 string address = "http://www.jb51.net/?" + httputility.urlencode("参数一", myencoding) + "=" + httputility.urlencode("值一", myencoding);
httpwebrequest req = (httpwebrequest)httpwebrequest.create("http://localhost/winformpost/default.aspx?act=aabbcc");
req.method = "get";
using (webresponse wr = req.getresponse())
{
//在这里对接收到的页面内容进行处理
using (streamreader reader = new streamreader(wr.getresponsestream(),myencoding))
{

string body = reader.readtoend();
reader.close();
messagebox.show(body);
}
}
}

private void button2_click(object sender, eventargs e)
{
//post
string parmer = "act=send&name=abcd";
byte[] bytes = encoding.ascii.getbytes(parmer);
httpwebrequest req = (httpwebrequest)httpwebrequest.create("http://localhost/winformpost/default.aspx");
req.method = "post";
req.contenttype = "application/x-www-form-urlencoded";
req.contentlength = bytes.length;
using (stream reqstream = req.getrequeststream())
{
reqstream.write(bytes, 0, bytes.length);
}
using (webresponse wr = req.getresponse())
{
using (streamreader sr = new streamreader(wr.getresponsestream()))
{
messagebox.show(sr.readtoend());
}
}
}

private void button3_click(object sender, eventargs e)
{
httpwebrequest req = (httpwebrequest)httpwebrequest.create("http://localhost/winformpost/default.aspx");
req.method = "post";
filestream fs = new filestream("d:\\12.jpg", filemode.open, fileaccess.read);
byte[] postdatabyte = new byte[fs.length];
fs.read(postdatabyte, 0, postdatabyte.length);
req.contentlength = postdatabyte.length;
stream stream = req.getrequeststream();
stream.write(postdatabyte, 0, postdatabyte.length);
stream.close();
using (webresponse wr = req.getresponse())
{
using (streamreader sr = new streamreader(wr.getresponsestream()))
{
messagebox.show(sr.readtoend());
}
}
}
private void button4_click(object sender, eventargs e)
{
uploadimage("d:\\常用软件\\数据库\\sql2008full_chs.iso");
}

/// <summary>
/// 通过http上传图片及传参数
/// </summary>
/// <param name="imgpath">图片地址(绝对路径:d:\demo\img\123.jpg)</param>
public void uploadimage(string imgpath)
{
var uploadurl = "http://localhost/winformpost/up.aspx";
dictionary<string, string> dic = new dictionary<string, string>() {
{"p1",1.tostring() },
{"p2",2.tostring() },
{"p3",3.tostring() },
};
var postdata = "p1=1&fname=sql2008full_chs.iso&p3=3";// utils.buildquery(dic);//转换成:para1=1&para2=2&para3=3,后台获取参数将以querystring方式 ,而非 form方式
var posturl = string.format("{0}?{1}", uploadurl, postdata);//拼接url
httpwebrequest request = webrequest.create(posturl) as httpwebrequest;
request.allowautoredirect = true;
request.method = "post";

string boundary = datetime.now.ticks.tostring("x"); // 随机分隔线
request.contenttype = "multipart/form-data;charset=utf-8;boundary=" + boundary;
byte[] itemboundarybytes = encoding.utf8.getbytes("\r\n--" + boundary + "\r\n");
byte[] endboundarybytes = encoding.utf8.getbytes("\r\n--" + boundary + "--\r\n");

int pos = imgpath.lastindexof("\\");
string filename = imgpath.substring(pos + 1);

//请求头部信息
stringbuilder sbheader = new stringbuilder(string.format("content-disposition:form-data;name=\"file\";filename=\"{0}\"\r\ncontent-type:application/octet-stream\r\n\r\n", filename));
byte[] postheaderbytes = encoding.utf8.getbytes(sbheader.tostring());
stream poststream = request.getrequeststream();
using (filestream fs = new filestream(imgpath, filemode.open, fileaccess.read))
{
//发送分隔符
poststream.write(itemboundarybytes, 0, itemboundarybytes.length);
//发送头部信息
poststream.write(postheaderbytes, 0, postheaderbytes.length);
//写文件
byte[] filebytes = new byte[1024];
int filebyteread = 0;
while ((filebyteread =fs.read(filebytes,0,filebytes.length)) !=0 )
{
poststream.write(filebytes, 0, filebyteread);
}
}
//发送分隔符
poststream.write(endboundarybytes, 0, endboundarybytes.length);
poststream.close();

httpwebresponse response = request.getresponse() as httpwebresponse;
//stream instream = response.getresponsestream();
//streamreader sr = new streamreader(instream, encoding.utf8);
//string content = sr.readtoend();
//messagebox.show(content);
using (stream responsestream = response.getresponsestream())
{
using (streamreader mystreamreader = new streamreader(responsestream, encoding.getencoding("utf-8")))
{
string retstring = mystreamreader.readtoend();
messagebox.show( retstring);
}
}

}

private void button5_click(object sender, eventargs e)
{
openfiledialog openfiledialog1 = new openfiledialog();
openfiledialog1.initialdirectory = "c:\\";//注意这里写路径时要用c:\\而不是c:\
openfiledialog1.filter = "图片|*.jpg|png|*.png|所有文件|*.*";
openfiledialog1.restoredirectory = true;
openfiledialog1.filterindex = 1;
if (openfiledialog1.showdialog() == dialogresult.ok)
{
try
{
string path = openfiledialog1.filename;
webclient wc = new webclient();
wc.credentials = credentialcache.defaultcredentials;
wc.headers.add("content-type", "application/x-www-form-urlencoded");
// wc.headers.add("content-type", "multipart/form-data");
//wc.querystring["fname"] = openfiledialog1.safefilename;//没用
//messagebox.show(openfiledialog1.safefilename);
byte[] fileb = wc.uploadfile(new uri(@"http://localhost/winformpost/up.aspx?p1=webclient&fname=" + openfiledialog1.safefilename), "post", path);
string res = encoding.getencoding("gb2312").getstring(fileb);
wc.dispose();
messagebox.show(res);
}
catch (exception ex)
{
messagebox.show(ex.message);
}

}
}
//上传文件:要设置共享文件夹是否有创建的权限,否则无法上传文件uploadfile("d:\\1.jpg", "http://localhost/winformpost/up.aspx", "", "");
public void uploadfile(string filenamepath, string urlpath, string user, string pwd)
{
string newfilename = filenamepath.substring(filenamepath.lastindexof(@"\") + 1);//取文件名称
messagebox.show(newfilename);
if (urlpath.endswith(@"\") == false) urlpath = urlpath + @"\";

urlpath = urlpath + newfilename;

webclient mywebclient = new webclient();
//networkcredential cread = new networkcredential(user, pwd, "domain");
//mywebclient.credentials = cread;
filestream fs = new filestream(filenamepath, filemode.open, fileaccess.read);
binaryreader r = new binaryreader(fs);

try
{
byte[] postarray = r.readbytes((int)fs.length);
stream poststream = mywebclient.openwrite(urlpath);
// poststream.m
if (poststream.canwrite)
{
poststream.write(postarray, 0, postarray.length);
messagebox.show("文件上传成功!", "提醒", messageboxbuttons.ok, messageboxicon.information);
}
else
{
messagebox.show("文件上传错误!", "警告", messageboxbuttons.ok, messageboxicon.warning);
}

poststream.close();
}
catch (exception ex)
{
messagebox.show(ex.message, "错误");
}

}


}
}


 

后端

 

using system;
using system.collections.generic;
using system.linq;
using system.web;
using system.web.ui;
using system.web.ui.webcontrols;

namespace winformpost
{
public partial class up : system.web.ui.page
{
protected void page_load(object sender, eventargs e)
{
httppostedfile f;
if (request.files.count > 0)
{
for (int i = 0; i < request.files.count; i++)
{
f = request.files[i];
string fname = request.querystring["fname"];
if (string.isnullorempty(fname) == false)
f.saveas(server.mappath("~/uploadfiles/") + fname);
else
{
random rnd = new random();
f.saveas(server.mappath("~/uploadfiles/") +rnd.next(99999)+ "_002.jpg");
}
}

}
string p1 = request["p1"];
if (string.isnullorempty(p1)==false)
{
response.write("p1=" + p1);
}
response.write("\r\nend");
response.end();
}
}
}