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¶2=2¶3=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();
}
}
}
WinForm POST上传与后台接收的更多相关文章
- 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密
你真的了解字典(Dictionary)吗? 从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...
- 由于ios由UIWebView换成了WKWebview内核后导致webview请求接口文件上传,后台接收不到文件
2020年4月起App Store将不再接受使用UIWebView的新App上架.2020年12月起将不再接受使用UIWebView的App更新. 解决后台文件接收不到的问题 function GLA ...
- Android实现TCP断点上传,后台C#服务实现接收
终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现,因为大多实现过断点下载.但稳定性不能保证, ...
- 实现TCP断点上传,后台C#服务实现接收
实现TCP断点上传,后台C#服务实现接收 终端实现大文件上传一直都是比较难的技术,其中涉及到后端与前端的交互,稳定性和流量大小,而且实现原理每个人都有自己的想法,后端主流用的比较多的是Http来实现, ...
- SNF开发平台WinForm之六-上传下载组件使用-SNF快速开发平台3.3-Spring.Net.Framework
6.1运行效果: 6.2开发实现: 1.先在要使用的项目进行引用,SNF.WinForm.Attachments.dll文件. 2.在工具箱内新建选项卡->选择项,浏览找到文件SNF.WinFo ...
- 动态input file多文件上传到后台没反应的解决方法!!!
其实我也不太清除具体是什么原因,但是后面就可以了!!! 我用的是springMVC 自带的文件上传 1.首先肯定是要有springMVC上传文件的相关配置! 2.前端 这是动态input file上传 ...
- django设置并获取cookie/session,文件上传,ajax接收文件,post/get请求及跨域请求等的方法
django设置并获取cookie/session,文件上传,ajax接收文件等的方法: views.py文件: from django.shortcuts import render,HttpRes ...
- MVC 手机端页面 使用标签file 图片上传到后台处理
最近刚做了一个头像上传的功能,使用的是H5 的界面,为了这个功能搞了半天的时间,找了各种插件,有很多自己都不知道怎么使用,后来只是使用了一个标签就搞定了:如果对样式没有太大的要求我感觉使用这个就足够了 ...
- plupload批量上传分片(后台代码)
plupload批量上传分片功能, 对于文件比较大的情况下,plupload支持分片上传,后台代码如下: /** * * 方法:upLoadSpecialProgramPictrue * 方法说明:本 ...
随机推荐
- Subarray Sum Equals K LT560
Given an array of integers and an integer k, you need to find the total number of continuous subarra ...
- InputMethodManagerService处理输入法——监听APK变动
android\frameworks\base\services\java\com\android\server\InputMethodManagerService.java public Input ...
- Spring Boot学习笔记:ApplicationEvent和ApplicationEventListener事件监听
采用事件监听的好处 以用户注册的业务逻辑为例,用户在填写完信息表单后,提交信息到后台,后台对用户信息进行处理,然后给用户返回处理结果的信息. 如上图所示,用户在注册时,后台需要处理一些系列流程,实际业 ...
- 计算器的改良(NOIP2000)
题目链接:计算器的改良 这道题,不是很难,但代码也短不到哪去. 我们这里决定采取边读入边计算的方法,因为题目没有明确说式子有多长. 我们需要计算什么? 我们需要知道等号两边未知数的系数和常数项即可. ...
- php结合layui实现前台加后台操作
一:前台加载出前端页面: HTML: lay-data="{width:800,height:400, url:'data.php', page:true, id:'test'} js: l ...
- denyhost安装脚本
#!/bin/bashDENYHOSTS=DenyHosts-2.6.tar.gzDENYHOSTS_VERSION=DenyHosts-2.6DENYHOSTS_URL=http://192.168 ...
- screen对象和history对象
history对象保存着用户上网的历史记录,从窗口被打开的那一刻开始算起 使用go()方法可以在用户的历史记录中任意跳转 history.go(-1);//后退一页 history.go(1);//前 ...
- Python写出LSTM-RNN的代码
0. 前言 本文翻译自博客: iamtrask.github.io ,这次翻译已经获得trask本人的同意与支持,在此特别感谢trask.本文属于作者一边学习一边翻译的作品,所以在用词.理论方面难免会 ...
- HDMI之HPD
HDMI(19Pin)/DVI(16 pin)的功能是热插拔检测(Hot Plug Detect,HPD),这个信号将作为主机系统是否对HDMI/DVI是否发送TMDS信号的依据.HPD是从显示器输出 ...
- Hibernate关联关系配置(一对多,一对一,多对多)
一对多 创建两个类 Manager(一这一端) Worker(多这一端) 即一个经理下有多个员工 package com.hibernate.n21; import java.util.HashS ...