WinForm POST上传与后台接收

前端



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();
}
}
}

原文地址:https://www.cnblogs.com/xxxy/p/10357633.html

时间: 2024-10-11 13:16:31

WinForm POST上传与后台接收的相关文章

实现TCP断点上传,后台C#服务实现接收

实现TCP断点上传,后台C#服务实现接收 终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现,因为大多实现过断点下载.但稳定性不能保证,一旦断开,无法续传.所以得采用另一种流行的做法,TCP上传大文件. 网上查找了一些资料,大多数是断点下载,然后就是单独的C#端的上传接收,或是HTTP的,或是只有android端的,由于任务紧所以之前找的首选方案当然是Http先来实现文件上传,终端采用Pos

动态input file多文件上传到后台没反应的解决方法!!!

其实我也不太清除具体是什么原因,但是后面就可以了!!! 我用的是springMVC 自带的文件上传 1.首先肯定是要有springMVC上传文件的相关配置! 2.前端 这是动态input file上传到后台没反应的写法(页面上写死的上传到后台是可以的) 这段代码是写在table>>下的form表单里的 <input type="button" name="button" value="添加附件" onclick="ad

plupload批量上传分片(后台代码)

plupload批量上传分片功能, 对于文件比较大的情况下,plupload支持分片上传,后台代码如下: /** * * 方法:upLoadSpecialProgramPictrue * 方法说明:本地节目导入 * @return * @author wangHao * @throws Exception * @date 2015年6月9日 */ @RequestMapping("/localUpLoadProgram") @ResponseBody public void local

说说ajax上传数据和接收数据

我是一个脑袋不太灵光的人,所以遇到问题,厚着脸皮去请教大神的时候,害怕被大神鄙视,但是还是被鄙视了.我说自己不要点脸面,那是不可能的,但是,为了能让自己的技术生涯能走的更长远一些,受点白眼,受点嘲笑也不算什么.重在被各种鄙视之后,我学到了什么,这才是关键的.好吧,我在自我安慰.哈哈,废话不多说啦,说正题. 我一直觉得ajax是个神奇的存在,但是之前我做的都是通过ajax去接收数据,栗如: $.ajax({ type: "get", url: "https://www.baid

springMVC file文件上传及参数接收

springMvc文件上传,首先两个基础, 1.form表单属性中加上enctype="multipart/form-data" 强调:form表单的<form method="post" ...,method必须有,我这里是用的是post,至于get行不行没试过,没有method="post"也会报不是multipart请求的错误. 2.配置文件中配置MultipartResolver 文件超出限制会在进入controller前抛出异常,

.NET 文件上传和文件接收

有时候,我们需要在后台端发起向指定的“文件接收接口”的文件传输请求,可以采用HttpWebRequest方式实现文件传输请求. 1.HttpWebRequest文件传输请求的代码如下: 其中,url为外部的文件接收接口,url中可以跟多个参数,如: http:project/Weixin/SaveUploadFile?path={0} filePath为待上传文件的物理路径 /// <summary> /// 传输文件到指定接口 /// </summary> /// <par

基于file上传文件的并发上传(多个文件一起上传到后台并把数据存储的同一条数据中,如 数据库字段videopath,imge。前台发送来的文件file1,file2。 videopath=file1,imge=file2)

前台代码: <div class="tab-content"> <dl> <dt>所属栏目</dt> <dd> <div class="rule-single-select"> <select id="ddlCategoryId"> <option value="0">所有栏目</option> </select&

微信小程序开发(二)图片上传+服务端接收

文/YXJ 地址:http://blog.csdn.net/sk719887916/article/details/54312573 前几天做了图片上传功能,被坑了一下.我们来看一下微信的上传api. 这里的filePath就是图片的存储路径,类型居然是个String,也就是 只能每次传一张图片,我以前的接口都是接收一个array,我本人又是一个半吊子的php,只能自己去改接收图片的接口. 看一下页面效果图 一个很常见的修改头像效果,选择图片(拍照),然后上传. 下面就是贴代码了 首先是小程序的

winform HttpWebRequest上传文件

Winform点击button按钮上传: string filePath = "E:\\test.rar"; string fileName = "test.rar"; string postURL = "http://localhost:5995/Default.aspx"; // 边界符 var boundary = "---------------" + DateTime.Now.Ticks.ToString("