在WinForm中通过HTTP协议向服务器端上传文件

合集下载

C#WinForm通过WebClient实现文件上传下载(附源码)

C#WinForm通过WebClient实现文件上传下载(附源码)

C#WinForm通过WebClient实现文件上传下载(附源码)[c-sharp]view plaincopy1.//// <summary>2./// WebClient上传文件至服务器3./// </summary>4./// <param name="fileNamePath">文件名,全路径格式</param>5./// <param name="uriString">服务器文件夹路径</param>6.private void UpLoadFile(string fileNamePath,string uriStri ng)7.{8.//string fileName = fileNamePath.Substring(fileNamePath .LastIndexOf("//") + 1);9.NewFileName = DateTime.Now.T oString("yyMMddhhmm ss") + lisecond.ToString() + fileNamePath.Sub string(stIndexOf("."));10.11.string fileNameExt = fileName.Substring(st IndexOf(".") + 1);12.if(uriString.EndsWith("/") == false) uriString = uriString + "/";13.14.uriString = uriString + NewFileName;15./**//// 创建WebClient实例16.WebClient myWebClient = new WebClient();17.myWebClient.Credentials = CredentialCache.DefaultCr edentials;18.19.// 要上传的文件20.FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);21.//FileStream fs = OpenFile();22.BinaryReader r = new BinaryReader(fs);23.try24.{25.//使用UploadFile方法可以用下面的格式26.//myWebClient.UploadFile(uriString,"PUT",fileNamePa th);27.byte[] postArray = r.ReadBytes((int)fs.Length);28.Stream postStream = myWebClient.OpenWrite(uriStrin g,"PUT");29.if(postStream.CanWrite)30.{31.postStream.Write(postArray,0,postArray.Length);32.}33.else34.{35.MessageBox.Show("文件目前不可写!");36.}37.postStream.Close();38.}39.catch40.{41.MessageBox.Show("文件上传失败,请稍候重试~");42.}43.}44.45.46./**//// <summary>47./// 下载服务器文件至客户端48.49./// </summary>50./// <param name="URL">被下载的文件地址,绝对路径</param>51./// <param name="Dir">另存放的目录</param>52.public void Download(string URL,string Dir)53.{54.WebClient client = new WebClient();55.string fileName = URL.Substring(stIndexOf("//") + 1); //被下载的文件名56.57.string Path = Dir+fileName; //另存为的绝对路径+文件名58.59.try60.{61.WebRequest myre=WebRequest.Create(URL);62.}63.catch64.{65.//MessageBox.Show(exp.Message,"Error");66.}67.68.try69.{70.client.DownloadFile(URL,Path);71.72.}73.catch74.{75.//MessageBox.Show(exp.Message,"Error");76.}77.}下载带进度条代码[c-sharp]view plaincopy1./// <summary>2./// 下载文件3./// </summary>4./// <param name="URL">网址</param>5./// <param name="Filename">文件名</param>6./// <param name="Prog">进度条</param>7.public static void DownFile( string URL, string Filename, P rogressBar Prog )8.{.HttpWebRequest Myrq = (.HttpW ebRequest).HttpWebRequest.Create(URL); //从URL地址得到一个WEB请求.HttpWebResponse myrp = (.Ht tpWebResponse)Myrq.GetResponse(); //从WEB请求得到WEB响应11.long totalBytes = myrp.ContentLength; //从WEB响应得到总字节数12.Prog.Maximum = (int)totalBytes; //从总字节数得到进度条的最大值13.System.IO.Stream st = myrp.GetResponseStream(); //从WEB请求创建流(读)14.System.IO.Stream so = new System.IO.FileStream(Filename, System.IO.FileMode.Create); //创建文件流(写)15.long totalDownloadedByte = 0; //下载文件大小16.byte[] by = new byte[1024];17.int osize = st.Read(by, 0, (int)by.Length); //读流18.while (osize > 0)19.{20.totalDownloadedByte = osize + totalDownloadedByte; //更新文件大小21.Application.DoEvents();22.so.Write(by, 0, osize); //写流23.Prog.Value = (int)totalDownloadedByte; //更新进度条24.osize = st.Read(by, 0, (int)by.Length); //读流25.}26.so.Close(); //关闭流27.st.Close(); //关闭流28.}。

flask文件上传原理

flask文件上传原理

flask文件上传原理Flask是一个轻量级的Web框架,可以进行文件上传和下载。

文件上传是指将本地计算机的文件传输到服务器上,而Flask的文件上传原理主要涉及了HTTP协议中的multipart/form-data和WTForms。

1. multipart/form-datamultipart/form-data是HTTP协议中的一种编码类型,用于在HTML表单中上传文件。

它将表单数据分为多个部分,并在每个部分中包含一个文件。

每个部分都包含一个Content-Disposition头字段,用于指定该部分的表单控件名称和文件名。

同时,还包含一个Content-Type头字段,用于指定该部分的MIME类型。

当客户端发送包含文件的表单请求时,服务器端将首先识别请求头中的Content-Type字段是否为multipart/form-data,如果是,则会解析请求体的内容,将文件以二进制流的形式存储到服务器的临时目录中。

Flask的文件上传机制就是基于这个原理实现的。

2. WTFormsWTForms是一个Python的表单验证库,可以生成HTML表单并进行数据验证。

它在Flask中起到了很重要的作用,因为Flask本身并不提供表单验证的功能。

在文件上传过程中,WTForms主要负责对表单数据进行验证。

它会对表单中的每个字段进行校验,包括文件大小、文件类型等。

如果校验通过,则将文件保存到指定的目录中,否则会返回相应的错误信息。

总结综上所述,Flask的文件上传原理主要涉及了HTTP协议中的multipart/form-data和WTForms。

其中,multipart/form-data用于在HTML表单中上传文件,WTForms则用于对表单数据进行验证。

在文件上传过程中,Flask会根据这两个原理,将文件以二进制流的形式存储到服务器的临时目录中,并在通过校验后将其保存到指定的位置。

Http服务器实现文件上传与下载

Http服务器实现文件上传与下载

Http服务器实现文件上传与下载(一)一、引言大家都知道web编程的协议就是http协议,称为超文本传输协议。

在J2EE中我们可以很快的实现一个Web工程,但在C++中就不是非常的迅速,原因无非就是底层的socket网络编写需要自己完成,上层的http协议需要我们自己完成,用户接口需要我们自己完成,如何高效和设计一个框架都是非常困难的一件事情。

但这些事情Java已经在底层为我们封装好了,而我们仅仅只是在做业务层上的事情吧了。

在本Http服务器实现中,利用C++库和socket原套接字编程和pthread线程编写。

拒绝使用第三方库。

因为主要是让大家知道基本的实现方式,除去一些安全、高效等特性,但是不管怎么样,第三方商业库的基本原理还是一致的,只是他们对其进行了优化而已。

在开始的编写时,我不会全部的简介Http的协议的内容,这样太枯燥了,我仅仅解释一些下面需要用到的协议字段。

在写本文的时候,之前也有些迷惑,C++到底能干啥,到网上一搜,无非就是能开发游戏,嵌入式编程,写服务器等等。

接着如果问如何编写一个服务器的话,那么这些网络水人又会告诉你,你先把基础学好,看看什么书,之后你就知道了,我只能呵呵了,在无目的的学习中,尽管看了你也不知道如何写的,因为尽管你知道一些大概,但是没有一个人领导你入门,我们还是无法编写一个我们自己想要的东西,我写这篇博客主要是做一个小小的敲门砖吧,尽管网上有许多博客,关于如何编写HTTP服务器的,但是要不是第三方库acl,要么就是短短的几行代码,要么就是加入了微软的一些C#内容或者MFC,这些在我看来只是一些无关紧要的东西,加入后或许界面上你很舒服,但是大大增加了我们的学习成本,因为这些界面上的代码改变了我们所知道的程序流程走向,还有一些界面代码和核心代码的混合,非常不利于学习。

二、HTTP协议在大家在浏览器的url输入栏上输入http://10.1.18.4/doing时。

WinForm中窗体间的数据传递(一)

WinForm中窗体间的数据传递(一)

WinForm中窗体间的数据传递(⼀)窗体间的数据传递的⼏种⽅法:1.通过⼦窗体的Tag属性2.借助第三⽅的⼀个静态变量3.通过⽗窗体的Tag属性局限性:必须得有⼀个窗体已经关闭,数据才能传递过去那如果,我们想在都不关闭任何窗体的情况下进⾏数据传递,该如何操作?在我的另外⼀篇博⽂中()可以借助向外引发事件来解决这个问题例⼦截图如下:当⽤户点击⼦窗⼝的“添加”按钮的时候的代码:private void button1_Click(object sender, EventArgs e){this.DialogResult = DialogResult.OK;//创建⼀个Info对象User info = new User();//将数据保存到Info对象中erName = textBox3.Text;info.PassWord = textBox4.Text;//问题:如何将info对象中的信息传递给主窗⼝//⽅案⼀:将对象info保存到⼦窗⼝的Tag属性中,则从⽗窗⼝中可以通过实例化的⼦窗⼝对象拿到info对象信息//this.Tag = info;//⽅案⼆:将对象info保存到⼀个静态变量中//第三⽅.user = info;//⽅案三:将对象info保存到⽗窗⼝的Tag属性中MainFrm mainfrm = this.Owner as MainFrm;mainfrm.Tag = info;}将⽤户点击主窗⼝中的“添加信息”的代码:private void添加⽤户ToolStripMenuItem_Click(object sender, EventArgs e){FrmUser userDialog = new FrmUser();if (userDialog.ShowDialog() == DialogResult.OK)//if (userDialog.ShowDialog(this) == DialogResult.OK){//⽅案⼀:通过⼦窗⼝的Tag属性进⾏窗体间的数据传递User user=userDialog.Tag as User;//⽅案⼆:借助第三⽅的⼀个静态属性进⾏数据传递User user = 第三⽅.user;//⽅案三:通过⽗窗⼝的Tag属性进⾏窗体间的数据传递,注意传递⼀个this参数给userDialog.ShowDialog()User user = this.Tag as User;MessageBox.Show("⽤户名:"+erName+"\r\n密码:" + user.PassWord);}}其中,得特别注意第三种⽅案,当将要传递的信息保存到“主窗⼝”的Tag中的时候,在显⽰“⼦窗⼝”的时候需要通过ShowDialog传递⼀个参数:this,⽤以设置当前窗体为⼦窗体的Owner原创⽂章,转载请注明出处:。

C# winform 上传文件 (多种方案)

C# winform 上传文件 (多种方案)
}
string fileNameExt = fileName.Substring(stIndexOf( " . " ) + 1 );
if (uriString.EndsWith( " / " ) == false ) uriString = uriString + " / " ;
Stream postStream = myWebClient.OpenWrite(uriString, " PUT " );
try
{
// 使用UploadFile方法可以用下面的格式
MPEG文件 .mpg,.mpeg video/mpeg
AVI文件 .avi video/x-msvideo
GZIP文件 .gz application/x-gzip
TAR文件 .tar application/x-tar
再然后
设置目标文件夹的可写性
using System;
/// winform形式的文件传输类
/// </summary>
public class WinFileTransporter
{
/**/ /// <summary>
/// WebClient上传文件至服务器,默认不自动改名
{
string fileName = fileNamePath.Substring(stIndexOf( " \\ " ) + 1 );
string NewFileName = fileName;
uriString = uriString + NewFileName;

winform通过HttpWebRequest(post方式)上传文件和传递参数

winform通过HttpWebRequest(post方式)上传文件和传递参数

winform通过HttpWebRequest(post⽅式)上传⽂件和传递参数1private void button1_Click(object sender, EventArgs e)2 {3 UploadFileHttpRequest(AppDomain.CurrentDomain.BaseDirectory. Trim() + "bb.txt");4 }5private string UploadFileHttpRequest(string fileName)6 {7string output = string.Empty;8 MemoryStream postStream = null;9 BinaryWriter postWriter = null;10 HttpWebResponse response = null;11 StreamReader responseStream = null;1213const string CONTENT_BOUNDARY = "----------ae0cH2cH2GI3Ef1 KM7GI3Ij5cH2gL6";14const string CONTENT_BOUNDARY_PREFIX = "--";1516try17 {18 UriBuilder uriBuilder = new UriBuilder("http://localhost:7408/ WebT/t.aspx");19 HttpWebRequest request = (HttpWebRequest)WebRequest.Cre ate(uriBuilder.Uri);20 /doc/82cd1c8f0b4e767f5bcfce1c.html erAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Wind ows NT 5.2; SV1; Maxthon; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";21 request.Timeout = 300000;22 request.ContentType = "multipart/form-data; boundary=" + C ONTENT_BOUNDARY;23 postStream = new MemoryStream();24 postWriter = new BinaryWriter(postStream);25//-- 参数26 //param['setType']27 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX +CONTENT_BOUNDARY + "\r\n" +28"Content-Disposition: form-data; name=\"param['setType']\" \ r\n\r\n"));29 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(" 2"));30 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\r\n"));31//param['startTime']32 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +33"Content-Disposition: form-data; name=\"param['startTime']\" \r\n\r\n"));34 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("" ));35 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));36//param['endTime']37 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +38"Content-Disposition: form-data; name=\"param['endTime']\" \r\n\r\n"));39 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("" ));40 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));41//param['resourceID']42 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +43"Content-Disposition: form-data; name=\"param['resourceID'] \" \r\n\r\n"));44 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(" 1398130"));45 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));46//forwardUrl47 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +48"Content-Disposition: form-data; name=\"forwardUrl\" \r\n\r\ n"));49 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("/ cs/showBatchToneInfoStart.action"));50 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));51//uploadFiles52 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +53"Content-Disposition: form-data; name=\"uploadFiles\" \r\n\r\ n"));54 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(fil eName));55 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));56byte[] fileContent = File.ReadAllBytes(fileName);57 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "\r\n" +58"Content-Disposition: form-data; name=\"FileContent\" " +59"filename=\"" + Path.GetFileName(fileName) + "\"\r\n\r\n"));60 postWriter.Write(fileContent);61 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes("\ r\n"));62 postWriter.Write(Encoding.GetEncoding("gb2312").GetBytes(C ONTENT_BOUNDARY_PREFIX + CONTENT_BOUNDARY + "--"));6364 request.ContentLength = postStream.Length;65 request.Method = "POST";66 Stream requestStream = request.GetRequestStream();67 postStream.WriteTo(requestStream);68 response = (HttpWebResponse)request.GetResponse();6970for (int i = 0; i < response.Headers.Count; i++)71 {72 output += response.Headers.Keys[i] + ": " + response.Get ResponseHeader(response.Headers.Keys[i]) + "\r\n";73 }74 Encoding enc = Encoding.GetEncoding("gb2312");7576try77 {78if (response.ContentEncoding.Length > 0) enc = Encoding.G etEncoding(response.ContentEncoding);79 }80catch { }81 responseStream = new StreamReader(response.GetResponseS tream(), enc);82 output += "\r\n\r\n\r\n" + responseStream.ReadToEnd();83 }84finally85 {86if (postWriter != null) postWriter.Close();87if (postStream != null)88 {89 postStream.Close();90 postStream.Dispose();91 }92if (response != null) response.Close(); 93if (responseStream != null)94 {95 responseStream.Close();96 responseStream.Dispose();97 }98 }99return output;100 }。

关于在WinForm里用HttpWebRequest获得某个页面,并填写页面的textbox及点击button的方法

关于在WinForm里用HttpWebRequest获得某个页面,并填写页面的textbox及点击button的方法
{
//指定的一个信息,将用于填写TextBoxFileName。
m_fileName = fileName;
//指定的URL
m_host = hostUrl;
}
public bool SendCompleteMessage(string user,string password)
writeStream.Close();
//下载回应消息。
string serverMessage = "";
try
{
response1 = request1.GetResponse();
//这里的response1是Server在Button点击后跳转到的另一个页面,这个页面有一个值表示是否成功
tempData.Append(HttpUtility.UrlEncode(aspValue));
//填写TextBoxFileName的值,其值见后
tempData.Append("&TextBoxFileName=");
tempData.Append("(content1)");
{
//得到页面数据段
aspValue = content.Substring(index,endIndex-index);
StringBuilder tempData = new StringBuilder();
tempData.Append("__VIEWSTATE=");
}
serverMessage = hehe1.ToString();
}
catch(Exception E)

PHP实现文件上传

PHP实现文件上传
名字必须是MAX_FILE_SIZE 值的单位是Byte字节,针对个人的应用程序更改大小。
使用$_FILES超级全局数组获取上传 文件信息
假设表单的文件框名字为photoFile,则: $_FILES[‘photoFile’][‘tmp_name’]
文件在Web服务器中临时存储的位置
$_FILES[‘pho件的函数
•move_uploaded_file(file,newloc) 函数将上传的文件 移动到新位置。若成功,则返回 true,否则返回 false。file:要移动的文件;newloc:移动的目标位置 •is_uploaded_file(file) 函数判断指定的文件是否是通 过 HTTP POST 上传的。是的话返回true,否则返回 false。
常见问题
不应该允许任何人上传文件,需要用户通 过身份验证 对上传文件进行重命名 基于Windows系统,把文件路径中的”\”改 为”\\”。 如果无法上传,查看php.ini中的配置信息 。
php.ini文件的设置
file_uploads on 是否允许通过HTTP上传文件的开关。默认为ON即 是开 upload_tmp_dir -- 文件上传至服务器上存储临时文件的地方,如果 没指定就会用系统默认的临时文件夹 upload_max_filesize 即允许上传文件大小的最大值。默认为2M post_max_size 指通过表单POST给PHP的所能接收的最大值,包括 表单里的所有值。默认为8M 如果要上传>8M的大体积文件,只设置上述四项还不一定能行的通。 还得继续设置下面的参数。
客户端上传时的文件名
$_FILES[‘photoFile’][‘size’]
文件的大小,单位字节
$_FILES[‘photoFile’][‘type’]

C#http系列之以form-data方式上传多个文件及键值对集合到远程服务器

C#http系列之以form-data方式上传多个文件及键值对集合到远程服务器

C#http系列之以form-data⽅式上传多个⽂件及键值对集合到远程服务器系列⽬录类似于以下场景,将表单中的⽤户信息(包含附件)上传到服务器并保存到数据库中,<form id="form1" runat="server" action="UserManageHandler.ashx" method="post" enctype="multipart/form-data"><div>名称: <input type="text" name="uname" class="uname" /><br/>邮件: <input type="text" name="email" class="email" /><p/>附件1: <input type="file" name="file1" class="file" /><p/>附件2: <input type="file" name="file2" class="file" /><p/>附件3: <input type="file" name="file3" class="file" /><p/><input type="submit" name="submit" value="提交" /></div></form>如果是在传统的管理系统或者⽹站中,上传到发布的IIS站点下,使⽤的上传控件结合后台的 HttpContext.Request.Files的相关类与⽅法很简单的即可实现上述功能。

C#控制台使用http协议上传文件

C#控制台使用http协议上传文件

C#控制台使⽤http协议上传⽂件本代码演⽰控制台上传⽂件源代码下载 :1.⾸先搭建好测试⽹站添加 PostFile.aspx web窗体PostFile.aspx页⾯代码<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PostFile.aspx.cs" Inherits="WebPostFile.PostFile" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="/1999/xhtml"><head runat="server"><title></title></head><body><form id="form1" enctype="multipart/form-data" runat="server"><div><input id="txtUploadFile" type="file" size="49" runat="server"/><asp:Button ID="btnUploadFile" runat="server" Text="上传⽂件" onclick="btnUploadFile_Click"/>&nbsp;<asp:Label Text="消息" ID="label" runat="server"/></div></form></body></html>界⾯如下上传⽂件后台代码protected void btnUploadFile_Click(object sender, EventArgs e){DateTime now = DateTime.Now;string strBaseLocation = "E:\\FileUpload\\";if (txtUploadFile.PostedFile.ContentLength != 0) //判断选取对话框选取的⽂件长度是否为0{txtUploadFile.PostedFile.SaveAs(strBaseLocation + DateTime.Now.ToString("yyyyMMddHHmmssfff")+ txtUploadFile.PostedFile.ContentLength.ToString()+ txtUploadFile.Value.Substring(stIndexOf('.')));//执⾏上传,并⾃动根据⽇期和⽂件⼤⼩不同为⽂件命名,确保不重复bel.Text = "⽂件上传成功";}}接下来是使⽤⽕狐浏览器演⽰上传为了观察使⽤FireBug上传之前先看看⽹页源代码点击上传查看页⾯源代码另外注意到 :响应:响应就是提交之后返回来的HTML:好了,到这⾥就差不多了.完整的过程演⽰结束,另外忘记介绍我上传的⽂件了我的⽂本⾥⾯只有⼀⾏⽂本我的⽬的是上传到 E:/FileUpload⽂件夹下接下来我们分析fireBug拦截到的 POST的内容部分multipart/form-data__VIEWSTATE/wEPDwUJNTkwMTM1MzYwZGTQdPOkKrqCzuS6U08K1OUNLYB6ZQKjWP8IiupbB7zRtg==__EVENTVALIDATION/wEdAAJVc7gpfEPU81Fw+WJFr67FNxe84VETfdT7HCr4G0JRBA8RfrOeF234+5KtY+F0Ckt2AxC02dJoVyvZBVupj91r txtUploadFile这是正式上传的⽂件.你好,这是我的测试内容btnUploadFile上传⽂件然后下⾯是源代码,这⾥⾯就是发送过来的内容⼀定要注意有换⾏别的不多说,相关的协议什么的,⾃⼰去查然后我直接上控制台模拟上传代码注意添加引⽤引⽤命名空间using System.IO;using ;class Program{///<summary>/// http协议 Content-Type 对照表///</summary>static Dictionary<string, string> dictContentType = new Dictionary<string, string>();static void InitHttpContentTypeDict(){dictContentType.Add(".css", "text/css");dictContentType.Add(".dll", "application/x-msdownload");dictContentType.Add(".htm", "text/html");dictContentType.Add(".jpg", "image/jpg");dictContentType.Add(".js ", "application/x-javascript");dictContentType.Add(".png", "image/png");dictContentType.Add(".ppt", "application/vnd.ms-powerpoint");dictContentType.Add(".txt", "text/plain");dictContentType.Add(".xls", "application/vnd.ms-excel");dictContentType.Add(".xsl", "text/xml");dictContentType.Add(".xml", "text/xml");dictContentType.Add(".xhtml", "text/xml");dictContentType.Add(".mp4", "video/mpeg4");dictContentType.Add(".jpeg", "image/jpeg");dictContentType.Add(".img", "application/x-img");dictContentType.Add(".html", "text/html");dictContentType.Add(".gif", "image/gif");dictContentType.Add(".*", "application/octet-stream");//⼆进制⽂件流}static void Main(string[] args){Program _pp = new Program();InitHttpContentTypeDict();string filePath = "d:\\121.txt";string fileType = filePath.Substring(stIndexOf('.'));string fileName = filePath.Substring(stIndexOf("\\") + 1);string contentType = dictContentType.Where(d => d.Key == fileType).Select(k => k.Value).First().ToString();StringBuilder sb = new StringBuilder();sb.Append("-----------------------------1837530724682\r\n");sb.Append("Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n");sb.Append("/wEPDwUJNTkwMTM1MzYwZGTQdPOkKrqCzuS6U08K1OUNLYB6ZQKjWP8IiupbB7zRtg==\r\n");sb.Append("-----------------------------1837530724682\r\n");sb.Append("Content-Disposition: form-data; name=\"__EVENTVALIDATION\"\r\n\r\n");sb.Append("/wEdAAJVc7gpfEPU81Fw+WJFr67FNxe84VETfdT7HCr4G0JRBA8RfrOeF234+5KtY+F0Ckt2AxC02dJoVyvZBVupj91r\r\n"); sb.Append("-----------------------------1837530724682\r\n");sb.Append("Content-Disposition: form-data; name=\"txtUploadFile\"; filename=\"" + fileName + "\"\r\n");sb.Append("Content-Type: " + contentType + "\r\n\r\n");byte[] byte_head = Encoding.UTF8.GetBytes(sb.ToString());byte[] byte_body = File.ReadAllBytes(filePath);sb.Clear();sb.Append("\r\n");sb.Append("-----------------------------1837530724682\r\n");sb.Append("Content-Disposition: form-data; name=\"btnUploadFile\"\r\n\r\n");sb.Append("Button\r\n");sb.Append("-----------------------------1837530724682--\r\n");byte[] byte_foot = Encoding.UTF8.GetBytes(sb.ToString());byte[]byteData = new byte[byte_head.Length+byte_body.Length+byte_foot.Length];for (int i = 0; i < byte_head.Length; i++){byteData[i] = byte_head[i];}for (int i = 0; i < byte_body.Length; i++){byteData[i+byte_head.Length] = byte_body[i];}for (int i = 0; i < byte_foot.Length; i++){byteData[i + byte_head.Length + byte_body.Length] = byte_foot[i];}string mess = _pp.Post("http://localhost:8776/PostFile.aspx", byteData);Console.WriteLine(mess);Console.ReadLine();}public string Post(string url, byte[] buffData){try{HttpWebRequest req = (HttpWebRequest)WebRequest.Create(new Uri(url));erAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0";req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8";req.Referer = "http://localhost:8776/WebForm1.aspx";byte[] buff = buffData;req.Method = "POST";req.ContentType = "multipart/form-data; boundary=---------------------------1837530724682";req.ContentLength = buff.Length;Stream reqStream = req.GetRequestStream();reqStream.Write(buff, 0, buff.Length);HttpWebResponse res = (HttpWebResponse)req.GetResponse();StreamReader sr = new StreamReader(res.GetResponseStream(), Encoding.UTF8);string mess = sr.ReadToEnd();sr.Close();res.Close();reqStream.Close();return mess;}catch (Exception){throw;}}}完整类需要说明的是 :sb.Append("Content-Disposition: form-data; name=\"__VIEWSTATE\"\r\n\r\n");sb.Append("/wEPDwUJNTkwMTM1MzYwZGTQdPOkKrqCzuS6U08K1OUNLYB6ZQKjWP8IiupbB7zRtg==\r\n");sb.Append("-----------------------------1837530724682\r\n");sb.Append("Content-Disposition: form-data; name=\"__EVENTVALIDATION\"\r\n\r\n");sb.Append("/wEdAAJVc7gpfEPU81Fw+WJFr67FNxe84VETfdT7HCr4G0JRBA8RfrOeF234+5KtY+F0Ckt2AxC02dJoVyvZBVupj91r\r\n");拼接的字符串 __VIEWSTATE 和 __EVENTVALIDATION ⼀定要跟⽹站上的⼀模⼀样,可以从新开⼀个页⾯然后查看页⾯原代码得到运⾏Main⽅法得到结果 (本⼈使⽤ Test Driven开发驱动进⾏测试)恩,然后查看上传⽂件夹好了,⼤功告成!当然上传不⼀定是上传 txt的⽂本,我们还可以上传图⽚,Excel,等等,经过测试,上传⽂本,jpg的图⽚,Excel xls⽂件都可以最后 : 将源代码奉上. ⾥⾯包括⽹站的,以及控制台的源代码下载:。

在WinForm中通过HTTP协议向服务器端上传文件

在WinForm中通过HTTP协议向服务器端上传文件

在WinForm中通过HTTP协议向服务器端上传⽂件相信⽤写⼀个上传⽂件的⽹页,⼤家都会写,但是有没有⼈想过通过在WinForm中通过HTTP协议上传⽂件呢?有些⼈说要向服务器端上传⽂件,⽤FTP协议不是很简单吗?效率⼜⾼,为什么还要使⽤HTTP协议那么⿇烦呢?这⾥⾯有⼏个原因:(1)的部署相对⿇烦,还要设置权限,权限设置不对,还会惹来⼀系列的安全问题。

(2)如果双⽅都还有防⽕墙,⼜不想开发FTP相关的⼀些端⼝时,HTTP就会⼤派⽤场,就像WEB Services能穿透防⽕墙⼀样。

(3)其他的...,还在想呢...但是使⽤HTTP也有他的⼀些问题,例如不能断点续传,⼤⽂件上传很难,速度很慢,所以HTTP协议上传的⽂件⼤⼩不应该太⼤。

说了这么多,原归正传,⼀般来说,在Winform⾥通过HTTP上传⽂件有⼏种可选的⽅法:(1)前⾯提到的Web Services,就是⼀种很好的⽅法,通过编写⼀个WebMethod,包含有 byte[] 类型的参数,然后调⽤Web Services的⽅法,⽂件内容就会以Base64编码传到服务器上,然后重新保存即可。

using System;using System.Collections;using ponentModel;using System.Data;using System.Drawing;using System.Web;using System.Web.SessionState;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.UI.HtmlControls;namespace UploadFileWeb{/// <summary>/// WebForm1 的摘要说明。

/// </summary>public class WebForm1 : System.Web.UI.Page{private void Page_Load(object sender, System.EventArgs e){// 在此处放置⽤户代码以初始化页⾯foreach( string f in Request.Files.AllKeys){HttpPostedFile file = Request.Files[f];file.SaveAs(@"D:/Temp/" + file.FileName);}if( Request.Params["testKey"] != null ){Response.Write(Request.Params["testKey"]);}}#region Web 窗体设计器⽣成的代码override protected void OnInit(EventArgs e){//// CODEGEN: 该调⽤是 Web 窗体设计器所必需的。

在WinForm中通过HTTP协议向服务器端上传文件

在WinForm中通过HTTP协议向服务器端上传文件

在WinForm中通过HTTP协议向服务器端上传文件相信用写一个上传文件的网页大家都会写但是有没有人想过通过在WinForm中通过HTTP协议上传文件呢有些人说要向服务器端上传文件用FTP协议不是很简单吗效率又高为什么还要使用HTTP协议那么麻烦呢这里面有几个原因1FTP服务器的部署相对麻烦还要设置权限权限设置不对还会惹来一系列的安全问题。

2如果双方都还有防火墙又不想开发FTP相关的一些端口时HTTP就会大派用场就像WEB Services能穿透防火墙一样。

3其他的...还在想呢... 但是使用HTTP也有他的一些问题例如不能断点续传大文件上传很难速度很慢所以HTTP协议上传的文件大小不应该太大。

说了这么多原归正传一般来说在Winform里通过HTTP 上传文件有几种可选的方法1前面提到的Web Services就是一种很好的方法通过编写一个WebMethod包含有byte 类型的参数然后调用Web Services的方法文件内容就会以Base64编码传到服务器上然后重新保存即可。

WebMethod public void UploadFilebyte contentstring filename... Stream sw new StreamWriter... sw.Close 当然这种通过Base64编码的方法效率比较低那么可以采用WSE支持附件并以2进制形式传送效率会更高。

2除了通过WebService另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTP的POST动作来实现。

这时候首先需要编写一个web form来响应上传代码如下ltDOCTYPE HTML PUBLIC quot-//W3C//DTD HTML 4.0 Transitional//ENquot gt lthtmlgt ltheadgt lttitlegtWebForm1lt/titlegt ltmeta namequotGENERATORquot ContentquotMicrosoft Visual Studio .NET 7.1quotgt ltmetanamequotCODE_LANGUAGEquot ContentquotCquotgt ltmeta namequotvs_defaultClientScriptquot contentquotJavaScriptquotgt ltmetanamequotvs_targetSchemaquotcontentquot/intellisense/ie5quotgt lt/headgt ltbodygt ltform idquotForm1quot methodquotpostquot runatquotserverquotgt lt/formgt lt/bodygt lt/htmlgt using System using System.Collections using ponentModel using System.Data using System.Drawing using System.Web using System.Web.SessionState using System.Web.UI using System.Web.UI.WebControls usingSystem.Web.UI.HtmlControls namespace UploadFileWeb ...///// ltsummarygt /// WebForm1 的摘要说明。

文件上传到HTTP服务器

文件上传到HTTP服务器

文件上传到HTTP服务器2011-03-14 17:15最近两个星期主要搞这个东东,到今天总算比较圆满的搞定了. 用http协议上传主要有两种形式: 第一是用http的put协议,第二是用http的post协议.先说说put协议, 所谓put,顾名思义,就是把文件"放"到server端. 这个过程不涉及文件的http和mime封装(post协议需要做), 因而比较简单.但是考虑到安全问题,一般服务器不会开发put权限,因此这种方法的用途并不广泛废话不多说,来看看代码:CInternetSession internetSession("my session"); //定义sessionCHttpConnection* httpConnection = internetSession.GetHttpConnection(strServerIP,intServerPort); //获得链接CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_PUT,strRemoteFile,NULL,0,NULL, NULL,INTERNET_FLAG_DONT_CACHE); //发送请求...httpFile->SendRequestEx(&BufferIn,NULL,HSR_INITIATE,0);注意倒数第二句的CHttpConnection::HTTP_VERB_PUT, 表示程序将采用http的put协议上传文件.再看post协议,这个东东如果只涉及文本还是比较简单的,可以直接post过去,不用构造表单. 但是一旦需要上传文件, 就需要用http和mime的两层封装了. 封装需要对http头和mime标识做一些了解,很恶心=,=. 最需要注意的一点, 在最后SendRequestEx的时候, 传递的参数是文件的字节数,这个字节数应该是所要上传的文件和http头以及mime头的字节总数! 否则即使CLIENT端不出错, server也得不到正确结果的!也来看看代码吧:CInternetSession internetSession("my session"); //定义sessionCHttpConnection* httpConnection=internetSession.GetHttpConnection(strServerIP,intServerPort); //获得链接CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST,strRemoteFile,NULL,0,NULL, NULL,INTERNET_FLAG_DONT_CACHE); //发送请求...httpFile->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);随便说说,post协议俺用baidu搜了许久,找到了一个类似的程序,研究了许久搞不定.. 后来目有办法, google一个外文论坛, 拜读了某牛人的大作后,终于弄清楚了~ 看来以后还是要多啃鸟文啊..附上源代码:put协议:UpLoadFile::UpLoadFile(void){}UpLoadFile::~UpLoadFile(void){}BOOL UpLoadFile::UseHttpSendReqEx(CHttpFile* httpFile, DWORD dwPostSize,CString strLocalFile){try{DWORD dwRead,dwRet;BYTE* buffer;TRACE("Local file:%sn",strLocalFile);FILE* fLocal;if((fLocal=fopen(strLocalFile,"rb"))==NULL){TRACE("Can't open the file:%s,maybe it doesn't exist!n",strLocalFile);return false;}fseek(fLocal,0L,SEEK_END);dwRead=ftell(fLocal);rewind(fLocal);buffer=(BYTE *)malloc(dwRead);if(!buffer){TRACE("not enough memory!n");return false;}TRACE("length of file:%dn",dwRead);dwRead=fread(buffer,1,dwRead,fLocal);dwPostSize=dwRead;INTERNET_BUFFERS BufferIn;DWORD dwBytesWritten;BOOL bRet;BufferIn.dwStructSize = sizeof( INTERNET_BUFFERS ); // Must be set or error will occurBufferIn.Next = NULL;BufferIn.lpcszHeader = NULL;BufferIn.dwHeadersLength = 0;BufferIn.dwHeadersTotal = 0;BufferIn.lpvBuffer = NULL;BufferIn.dwBufferLength = 0;BufferIn.dwBufferTotal = dwPostSize; // This is the only member used other than dwStructSize BufferIn.dwOffsetLow = 0;BufferIn.dwOffsetHigh = 0;httpFile->SendRequestEx(&BufferIn,NULL,HSR_INITIATE,0);//httpFile->SendRequestEx(dwPostSize);httpFile->Write( buffer, dwPostSize);if(!httpFile->EndRequest(0,0,0)){TRACE( "Error on HttpEndRequest %lu n", GetLastError());return FALSE;}fclose(fLocal);free(buffer);return TRUE;}catch (CInternetException* pEx){//catch errors from WinInet}return FALSE;}BOOL UpLoadFile::Upload(CString strLocalFile,CString strServerIP,CString strServerPort,CString strRemoteFile){try{DWORD dwPostSize=0;INTERNET_PORT intServerPort=atoi(strServerPort);CInternetSession internetSession("my session");CHttpConnection* httpConnection = internetSession.GetHttpConnection(strServerIP,intServerPort);if(httpConnection == NULL){TRACE( "Failed to connectn" );return FALSE;}CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_PUT,strRemoteFile,NULL,0,NULL, NULL,INTERNET_FLAG_DONT_CACHE);//CHttpFile* httpFile = httpConnection->OpenRequest(CHttpConnection::HTTP_VERB_PUT,strRemoteFile);if(httpFile == NULL){TRACE( "Failed to open request handlen" );return FALSE;}if(UseHttpSendReqEx(httpFile, dwPostSize,strLocalFile)){TRACE( "nSend Finished.n" );httpFile->Close();httpConnection->Close();internetSession.Close();return TRUE;}httpFile->Close();httpConnection->Close();internetSession.Close();}catch (CInternetException* pEx){//catch errors from WinInet}return FALSE;}post协议:bool CVoiceXCtrl::UploadPCM(){TCHAR tempFilePath[MAX_PATH];tempFilePath[0] = 0;GetEnvironmentVariable(_T("ProgramFiles"), tempFilePath, MAX_PATH); if (tempFilePath[0] == 0){strcpy(tempFilePath, "C:\Program Files");}strncat(tempFilePath, "\VoiceX\upload.pcm", MAX_PATH);monWave.Save(tempFilePath);int startp = m_StandardWavURL.ReverseFind('/');int namelen = m_StandardWavURL.GetLength()-startp-1;CString pcmname = m_StandardWavURL.Mid(startp+1,namelen);CString defServerName ="";CString defObjectName ="/upload/upload.jsp";// USES_CONVERSION;CInternetSession Session;CHttpConnection *pHttpConnection = NULL;INTERNET_PORT nPort = 8090;CFile fTrack;CHttpFile* pHTTP;CString strHTTPBoundary;CString strPreFileData;CString strPostFileData;DWORD dwTotalRequestLength;DWORD dwChunkLength;DWORD dwReadLength;DWORD dwResponseLength;TCHAR szError[MAX_PATH];void* pBuffer;LPSTR szResponse;CString strResponse;BOOL bSuccess = TRUE;CString strDebugMessage;if (FALSE == fTrack.Open(tempFilePath, CFile::modeRead | CFile::shareDenyWrite)){AfxMessageBox(_T("Unable to open the file."));return FALSE;}CString strFileName = "upload.pcm";int iRecordID = 1;strHTTPBoundary = _T("IllBeVerySurprisedIfThisTurnsUp");strPreFileData = MakePreFileData(strHTTPBoundary, pcmname, iRecordID);strPostFileData = MakePostFileData(strHTTPBoundary);AfxMessageBox(strPreFileData);AfxMessageBox(strPostFileData);dwTotalRequestLength = strPreFileData.GetLength() + strPostFileData.GetLength() + fTrack.GetLength();dwChunkLength = 64 * 1024;pBuffer = malloc(dwChunkLength);if (NULL == pBuffer){return FALSE;}try{pHttpConnection = Session.GetHttpConnection(defServerName,nPort);pHTTP = pHttpConnection->OpenRequest(CHttpConnection::HTTP_VERB_POST, _T("/upload/upload.jsp"));pHTTP->AddRequestHeaders(MakeRequestHeaders(strHTTPBoundary));pHTTP->SendRequestEx(dwTotalRequestLength, HSR_SYNC | HSR_INITIATE);#ifdef _UNICODEpHTTP->Write(W2A(strPreFileData), strPreFileData.GetLength());#elsepHTTP->Write((LPSTR)(LPCSTR)strPreFileData, strPreFileData.GetLength());#endifdwReadLength = -1;while (0 != dwReadLength)strDebugMessage.Format(_T("%u / %un"), fTrack.GetPosition(), fTrack.GetLength()); TRACE(strDebugMessage);dwReadLength = fTrack.Read(pBuffer, dwChunkLength);if (0 != dwReadLength){pHTTP->Write(pBuffer, dwReadLength);}}#ifdef _UNICODEpHTTP->Write(W2A(strPostFileData), strPostFileData.GetLength());#elsepHTTP->Write((LPSTR)(LPCSTR)strPostFileData, strPostFileData.GetLength());#endifpHTTP->EndRequest(HSR_SYNC);dwResponseLength = pHTTP->GetLength();while (0 != dwResponseLength){szResponse = (LPSTR)malloc(dwResponseLength + 1);szResponse[dwResponseLength] = '';pHTTP->Read(szResponse, dwResponseLength);strResponse += szResponse;free(szResponse);dwResponseLength = pHTTP->GetLength();}AfxMessageBox(strResponse);}catch (CException* e){e->GetErrorMessage(szError, MAX_PATH);e->Delete();AfxMessageBox(szError);bSuccess = FALSE;}pHTTP->Close();delete pHTTP;fTrack.Close();if (NULL != pBuffer){free(pBuffer);}return bSuccess;}CString CVoiceXCtrl::MakeRequestHeaders(CString& strBoundary){CString strFormat;CString strData;strFormat = _T("Content-Type: multipart/form-data; boundary=%srn");strData.Format(strFormat, strBoundary);return strData;}CString CVoiceXCtrl::MakePreFileData(CString& strBoundary, CString& strFileName, int iRecordID){CString strFormat;CString strData;strFormat += _T("--%s");strFormat += _T("rn");strFormat += _T("Content-Disposition: form-data; name="recordid"");strFormat += _T("rnrn");strFormat += _T("%i");strFormat += _T("rn");strFormat += _T("--%s");strFormat += _T("rn");strFormat += _T("Content-Disposition: form-data; name="trackdata"; filename="%s""); strFormat += _T("rn");strFormat += _T("Content-Type: audio/wav");strFormat += _T("rn");strFormat += _T("Content-Transfer-Encoding: binary");strFormat += _T("rnrn");strData.Format(strFormat, strBoundary, iRecordID, strBoundary, strFileName);return strData;}CString CVoiceXCtrl::MakePostFileData(CString& strBoundary){CString strFormat;CString strData;strFormat = _T("rn");strFormat += _T("--%s");strFormat += _T("rn");strFormat += _T("Content-Disposition: form-data; name="submitted""); strFormat += _T("rnrn");strFormat += _T("hello");strFormat += _T("rn");strFormat += _T("--%s--");strFormat += _T("rn");strData.Format(strFormat, strBoundary, strBoundary);return strData;}。

Http服务器实现文件上传与下载(五)

Http服务器实现文件上传与下载(五)

Http服务器实现⽂件上传与下载(五)⼀、引⾔欢迎⼤家和我⼀起编写Http服务器实现⽂件的上传和下载,现在我回顾⼀下在上⼀章节中提到的⼀些内容,之前我已经提到过⽂件的下载,在⽂件的下载中也提到了⽂件的续下载只需要在响应头中填写Content-Range这⼀字段,并且服务器的⽂件指针指向读取的指定位置开始读取传输。

在这⼀章节中我讲讲解⽂件的上传这⼀功能,讲完这⼀章节,⼤致的功能也全部完成,接着就是上⾯⽂件控制模块和⼀些资源模块。

在⽂件的上传中主要以HttpRequest类为主,在考虑⽂件的上传时我⼀点迷惑,到底把⽂件的上传功能是放到HttpResponse下还是在HttpRequest下,毕竟HttpResponse中有⼀些相应的⽂件下载功能,在添加⼀个⽂件上传功能也不为过。

但是我最终还是选择在HttpRequest中,原因是我主要是HttpResponse作为是服务器到浏览器发送内容,⽽HttpRequest作为浏览器到服务器发送内容。

这样下载和上传的功能就分别坐落在了HttpResponse和HttpRequest上了。

在完成功能上的归属问题后,接着直接上代码,在⽂件的上传中,涉及到C++流。

在这⾥其实⽤到不是很多的内容,但是这却是C++⼀个重要的⼀⼤块内容。

有时间和⼤家在⼀起复习这⼀块内容。

好了,接着上代码咯,上⼀章的内容有设计⼀些HttpRequest的代码,没有全部的包括进去。

⼆、HttpRequest头⽂件(include/httprequest.h)1 #ifndef HTTPREQUEST_H2#define HTTPREQUEST_H3 #include "socket.h"4 #include <map>5 #include <string>6 #include <fstream>7namespace Http{8class HttpRequest{9public:10 HttpRequest(TCP::Socket &c);11virtual ~HttpRequest();12 std::string getMethod() const;13 std::string getUrl() const;14 std::string getHost() const;15 std::map<std::string,std::string> getHeader(int confd) ;16 ssize_t upload(int confd,std::string filename);17protected:18private:19 std::string method;20 std::string url;21 std::string host;22 TCP::Socket &s;23 };24 }25#endif// HTTPREQUEST_H源⽂件(src/httprequest.cpp)1 #include "httprequest.h"2 #include "utils.h"3namespace Http{4 HttpRequest::HttpRequest(TCP::Socket &c):s(c){5 }67 HttpRequest::~HttpRequest(){8 }9 std::map<std::string,std::string> HttpRequest::getHeader(int confd){10char recvBuf[1024];11 memset(recvBuf,0,sizeof(recvBuf));12 s.server_read(confd,recvBuf,1024);13 std::cout<<recvBuf<<std::endl;14 std::map<std::string,std::string> mp =Utils::parseHeader(recvBuf);15 method =mp["Method"];16 url=mp["Url"];17 host=mp["Host"];18return mp;19 }20 ssize_t HttpRequest::upload(int confd,std::string filename){21char buf[1024];22 size_t n=0;23 ssize_t nread=0;24 std::string boundary;25 std::string file;26 std::ofstream outStream;27int readlineCount=1;28while(1){29 memset(buf,0,sizeof(buf));30 n=s.server_readline(confd,buf,sizeof(buf));31if(readlineCount==1){32 boundary=std::string(buf,buf+strlen(buf)-2);33 boundary+="--\r\n";34 std::cout<<boundary<<std::endl<<boundary.size();35 }else if(readlineCount==2){36int i=n;37while(buf[i]!='='){38if((buf[i]>='0'&&buf[i]<='9')39 ||(buf[i]>='a'&&buf[i]<='z')40 ||(buf[i]>='A'&&buf[i]<='Z')41 ||(buf[i]=='.'))42 i--;43else{44 buf[i]='*';45 i--;46 }47 }48 file=std::string(buf+i+2,buf+n-3);49 }else if(readlineCount==3){50 std::string rw;51 rw=std::string(buf,buf+strlen(buf));52int pos=rw.find('/');53 rw=rw.substr(0,pos);54 filename=filename+file;55if(rw=="Content-Type: text")56 outStream.open(filename.c_str());57else{58 outStream.open(filename.c_str(),std::ios::binary);59 std::cout<<"ios::binary"<<std::endl;60 }61 }else if(readlineCount==4){62 memset(buf,0,sizeof(buf));63while(1){64 n=s.server_readn(confd,buf,sizeof(buf));65if(n==boundary.size()&&strcmp(buf,boundary.c_str())==0){66goto exit;67 }68 nread+=n;69if(buf[n-1]==0){70 outStream.write(buf,n-1);71 }else{72 outStream.write(buf,n);73 }74 }75 }76 readlineCount++;77 }78 exit:79 outStream.close();80 s.server_close(confd);81return nread;82 }83 std::string HttpRequest::getMethod() const{84return method;85 }86 std::string HttpRequest::getUrl() const{87return url;88 }89 std::string HttpRequest::getHost() const{90return host;91 }92 }好了上传⽂件的代码也已经出来了,现在就是对其稍微的解释⼀下把。

c# winform 端口监听和文件的传输

c# winform 端口监听和文件的传输

c# winform 端口监听和文件的传输c# winform 端口监听和文件的传输不说那么多直接上代码代码中有注释服务器用来接收文件,不停的监听端口,有发送文件就马上开始接收文件服务端代码:代码using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using ;using System.Threading;using .Sockets;using System.IO;namespace TestSocketServerHSTF{public partial class Form1 : Form{public Form1(){InitializeComponent();//不显示出dataGridView1的最后一行空白dataGridView1.AllowUserToAddRows = false;}#region定义变量#endregion#region进入窗体即启动服务private void Form1_Load(object sender, EventArgs e){//开启接收线程Thread TempThread = new Thread(new ThreadStart(t his.StartReceive));TempThread.Start();}#endregion#region功能函数private void StartReceive(){//创建一个网络端点IPEndPoint ipep = new IPEndPoint(IPAddress.Any, int.Parse("2005"));//MessageBox.Show(IPAddress.Any);//创建一个套接字Socket server = new Socket(AddressFamily.InterNe twork, SocketType.Stream, ProtocolType.Tcp);//绑定套接字到端口server.Bind(ipep);//开始侦听(并堵塞该线程)server.Listen(10);//确认连接Socket client = server.Accept();//获得客户端节点对象IPEndPoint clientep = (IPEndPoint)client.RemoteE ndPoint;//获得[文件名]string SendFileName = System.Text.Encoding.Unico de.GetString(TransferFiles.ReceiveVarData(client));//MessageBox.Show("文件名" + SendFileName);//获得[包的大小]string bagSize = System.Text.Encoding.Unicode.Ge tString(TransferFiles.ReceiveVarData(client));//MessageBox.Show("包大小" + bagSize);//获得[包的总数量]int bagCount = int.Parse(System.Text.Encoding.Un icode.GetString(TransferFiles.ReceiveVarData(client)));//MessageBox.Show("包的总数量" + bagCount);//获得[最后一个包的大小]string bagLast = System.Text.Encoding.Unicode.Ge tString(TransferFiles.ReceiveVarData(client));//MessageBox.Show("最后一个包的大小" + bagLast);//创建一个新文件FileStream MyFileStream = new FileStream(SendFileName, FileMode.Create, FileAccess.Write);//已发送包的个数int SendedCount = 0;while (true){byte[] data = TransferFiles.ReceiveVarData(c lient);if (data.Length == 0){break;}else{SendedCount++;//将接收到的数据包写入到文件流对象MyFileStream.Write(data, 0, data.Length);//显示已发送包的个数//MessageBox.Show("已发送包个数"+SendedCoun t.ToString());}}//关闭文件流MyFileStream.Close();//关闭套接字client.Close();//填加到dgv里//文件大小,IP,已发送包的个数,文件名,包的总量,最后一个包的大小this.dataGridView1.Rows.Add(bagSize, clientep.A ddress, SendedCount, SendFileName, bagCount, bagLast);//MessageBox.Show("文件接收完毕!");}#endregion#region拦截Windows消息,关闭窗体时执行protected override void WndProc(ref Message m) {const int WM_SYSCOMMAND = 0x0112;const int SC_CLOSE = 0xF060;if (m.Msg == WM_SYSCOMMAND && (int)m.WParam == S C_CLOSE){//捕捉关闭窗体消息// User clicked close button//this.WindowState = FormWindowState.Minimiz ed;//把右上角红叉关闭按钮变最小化ServiceStop();}base.WndProc(ref m); }#endregion#region停止服务//停止服务private void ServiceStop() {try{}catch { }try{}catch { }}#endregion}}客户端用来发送文件,选择文件后点发送按钮发送文件客户端代码:代码using System;using System.Drawing;using System.Collections;using ponentModel;using System.Windows.Forms;using System.Data;using System.IO;using ;using .Sockets;using System.Threading;namespace发送端{///<summary>///Form1 的摘要说明。

c#form-data表单提交,postform上传数据、文件

c#form-data表单提交,postform上传数据、文件

c#form-data表单提交,postform上传数据、⽂件引⽤⾃:表单提交协议规定:要先将 HTTP 要求的 Content-Type 设为 multipart/form-data,⽽且要设定⼀个 boundary 参数,这个参数是由应⽤程序⾃⾏产⽣,它会⽤来识别每⼀份资料的边界 (boundary),⽤以产⽣多重信息部份 (message part)。

⽽ HTTP 服务器可以抓取 HTTP POST 的信息,基本内容:1. 每个信息部份都要⽤ --[BOUNDARY_NAME] 来包装,以分隔出信息的每个部份,⽽最后要再加上⼀个 --[BOUNDARY_NAME] 来表⽰结束。

2. 每个信息部份都要有⼀个 Content-Disposition: form-data; name="",⽽ name 设定的就是 HTTP POST 的键值 (key)。

3. 声明区和值区中间要隔两个新⾏符号(\r\n)。

4. 中间可以夹⼊⼆进制资料,但⼆进制资料必须要格式化为⼆进制字符串。

5. 若要设定不同信息段的资料型别 (Content-Type),则要在信息段内的声明区设定。

两个form内容模板boundary = "----" + DateTime.Now.Ticks.ToString("x");//程序⽣成1.⽂本内容"\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"键\"; filename=\"⽂件名\"" +"\r\nContent-Type: application/octet-stream" +"\r\n\r\n";2.⽂件内容"\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"键\"" +"\r\n\r\n内容";1.表⽰⼀个表单项的对象/// <summary>/// 表单数据项/// </summary>public class FormItemModel{/// <summary>/// 表单键,request["key"]/// </summary>public string Key { set; get; }/// <summary>/// 表单值,上传⽂件时忽略,request["key"].value/// </summary>public string Value { set; get; }/// <summary>/// 是否是⽂件/// </summary>public bool IsFile{get{if (FileContent==null || FileContent.Length == 0)return false;if (FileContent != null && FileContent.Length > 0 && string.IsNullOrWhiteSpace(FileName))throw new Exception("上传⽂件时 FileName 属性值不能为空");return true;}}/// <summary>/// 上传的⽂件名/// </summary>public string FileName { set; get; }/// <summary>/// 上传的⽂件内容/// </summary>public Stream FileContent { set; get; }} 2.提交表单主逻辑实现///<summary>///使⽤Post⽅法获取字符串结果///</summary>///<param name="url"></param>///<param name="formItems">Post表单内容</param>///<param name="cookieContainer"></param>///<param name="timeOut">默认20秒</param>///<param name="encoding">响应内容的编码类型(默认utf-8)</param>///<returns></returns>public static string PostForm(string url, List<FormItemModel> formItems, CookieContainer cookieContainer = null, string refererUrl = null, Encoding encoding = null,int timeOut = 20000) {HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);#region初始化请求对象request.Method = "POST";request.Timeout = timeOut;request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8";request.KeepAlive = true;erAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";if (!string.IsNullOrEmpty(refererUrl))request.Referer = refererUrl;if (cookieContainer != null)request.CookieContainer = cookieContainer;#endregionstring boundary = "----" + DateTime.Now.Ticks.ToString("x");//分隔符request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);//请求流var postStream = new MemoryStream();#region处理Form表单请求内容//是否⽤Form上传⽂件var formUploadFile = formItems != null && formItems.Count > 0;if (formUploadFile){//⽂件数据模板string fileFormdataTemplate ="\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"" +"\r\nContent-Type: application/octet-stream" +"\r\n\r\n";//⽂本数据模板string dataFormdataTemplate ="\r\n--" + boundary +"\r\nContent-Disposition: form-data; name=\"{0}\"" +"\r\n\r\n{1}";foreach (var item in formItems){string formdata = null;if (item.IsFile){//上传⽂件formdata = string.Format(fileFormdataTemplate,item.Key, //表单键item.FileName);}else{//上传⽂本formdata = string.Format(dataFormdataTemplate,item.Key,item.Value);}//统⼀处理byte[] formdataBytes = null;//第⼀⾏不需要换⾏if (postStream.Length == 0)formdataBytes = Encoding.UTF8.GetBytes(formdata.Substring(2, formdata.Length - 2));elseformdataBytes = Encoding.UTF8.GetBytes(formdata);postStream.Write(formdataBytes, 0, formdataBytes.Length);//写⼊⽂件内容if (item.FileContent != null && item.FileContent.Length>0){using (var stream = item.FileContent){byte[] buffer = new byte[1024];int bytesRead = 0;while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0){postStream.Write(buffer, 0, bytesRead);}}}}//结尾var footer = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n");postStream.Write(footer, 0, footer.Length);}else{request.ContentType = "application/x-www-form-urlencoded";}#endregionrequest.ContentLength = postStream.Length;#region输⼊⼆进制流if (postStream != null){postStream.Position = 0;//直接写⼊流Stream requestStream = request.GetRequestStream();byte[] buffer = new byte[1024];int bytesRead = 0;while ((bytesRead = postStream.Read(buffer, 0, buffer.Length)) != 0){requestStream.Write(buffer, 0, bytesRead);}////debug//postStream.Seek(0, SeekOrigin.Begin);//StreamReader sr = new StreamReader(postStream);//var postStr = sr.ReadToEnd();postStream.Close();//关闭⽂件访问}#endregionHttpWebResponse response = (HttpWebResponse)request.GetResponse();if (cookieContainer != null){response.Cookies = cookieContainer.GetCookies(response.ResponseUri);}using (Stream responseStream = response.GetResponseStream()){using (StreamReader myStreamReader = new StreamReader(responseStream, encoding ?? Encoding.UTF8)) {string retString = myStreamReader.ReadToEnd();return retString;}}}3.调⽤模拟post表单var url = "http://127.0.0.1/testformdata.aspx?aa=1&bb=2&ccc=3";var log1=@"D:\temp\log1.txt";var log2 = @"D:\temp\log2.txt";var formDatas = new List<.FormItemModel>();//添加⽂件formDatas.Add(new .FormItemModel(){Key="log1",Value="",FileName = "log1.txt",FileContent=File.OpenRead(log1)});formDatas.Add(new .FormItemModel(){Key = "log2",Value = "",FileName = "log2.txt",FileContent = File.OpenRead(log2)});//添加⽂本formDatas.Add(new .FormItemModel(){Key = "id",Value = "id-test-id-test-id-test-id-test-id-test-"});formDatas.Add(new .FormItemModel(){Key = "name",Value = "name-test-name-test-name-test-name-test-name-test-"});//提交表单var result = PostForm(url, formDatas);。

[C#]在WinForm下使用HttpWebRequest上传文件并显示进度

[C#]在WinForm下使用HttpWebRequest上传文件并显示进度

[C#]在WinForm下使用HttpWebRequest上传文件并显示进度[c-sharp]view plaincopyprint?1.在WinForm里面调用下面的方法来上传文件:2.3.// <summary>4./// 将本地文件上传到指定的服务器(HttpWebRequest方法)5./// </summary>6./// <param name="address">文件上传到的服务器</param>7./// <param name="fileNamePath">要上传的本地文件(全路径)</param>8./// <param name="saveName">文件上传后的名称</param>9./// <param name="progressBar">上传进度条</param>10./// <returns>成功返回1,失败返回0</returns>11.private int Upload_Request(string address, string fileN amePath, string saveName, ProgressBar progressBar)12.{13.int returnValue = 0;14.15.// 要上传的文件16.FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.Read);17.BinaryReader r = new BinaryReader(fs);18.19.//时间戳20.string strBoundary = "----------" + DateTime.Now.Ticks.ToString("x");21.byte[] boundaryBytes = Encoding.ASCII.GetBytes("/r/n --" + strBoundary + "/r/n");22.23.//请求头部信息24.StringBuilder sb = new StringBuilder();25.sb.Append("--");26.sb.Append(strBoundary);27.sb.Append("/r/n");28.sb.Append("Content-Disposition: form-data; name=/"");29.sb.Append("file");30.sb.Append("/"; filename=/"");31.sb.Append(saveName);32.sb.Append("/"");33.sb.Append("/r/n");34.sb.Append("Content-Type: ");35.sb.Append("application/octet-stream");36.sb.Append("/r/n");37.sb.Append("/r/n");38.string strPostHeader = sb.ToString();39.byte[] postHeaderBytes = Encoding.UTF8.GetBytes(str PostHeader);40.41.// 根据uri创建HttpWebRequest对象42.HttpWebRequest httpReq = (HttpWebRequest)WebRe quest.Create(new Uri(address));43.httpReq.Method = "POST";44.45.//对发送的数据不使用缓存46.httpReq.AllowWriteStreamBuffering = false;47.48.//设置获得响应的超时时间(300秒)49.httpReq.Timeout = 300000;50.httpReq.ContentType = "multipart/form-data; boundary=" + strBoundary;51.long length = fs.Length + postHeaderBytes.Length + boundaryBytes.Length;52.long fileLength = fs.Length;53.httpReq.ContentLength = length;54.try55.{56.progressBar.Maximum = int.MaxValue;57.progressBar.Minimum = 0;58.progressBar.Value = 0;59.60.//每次上传4k61.int bufferLength = 4096;62.byte[] buffer = new byte[bufferLength];63.64.//已上传的字节数65.long offset = 0;66.67.//开始上传时间68.DateTime startTime = DateTime.Now;69.int size = r.Read(buffer, 0, bufferLength);70.Stream postStream = httpReq.GetRequestStream();71.72.//发送请求头部消息73.postStream.Write(postHeaderBytes, 0, postHeaderByt es.Length);74.while (size > 0)75.{76.postStream.Write(buffer, 0, size);77.offset += size;78.progressBar.Value = (int)(offset * (int.MaxValue / length));79.TimeSpan span = DateTime.Now - startTime;80.double second = span.TotalSeconds;81.lblTime.Text = "已用时:" + second.ToString("F2") + "秒";82.if (second > 0.001)83.{84.lblSpeed.Text = " 平均速度:" + (offset / 1024 / second).ToString("0.00") + "KB/秒";85.}86.else87.{88.lblSpeed.Text = " 正在连接…";89.}90.lblState.Text = "已上传:" + (offset * 100.0 / length).ToString("F2") + "%";91.lblSize.Text = (offset / 1048576.0).ToString("F2") + "M/ " + (fileLength / 1048576.0).ToString("F2") + "M";92.Application.DoEvents();93.size = r.Read(buffer, 0, bufferLength);94.}95.//添加尾部的时间戳96.postStream.Write(boundaryBytes, 0, boundaryBytes.Le ngth);97.postStream.Close();98.99.//获取服务器端的响应100.WebResponse webRespon = httpReq.GetResponse(); 101.Stream s = webRespon.GetResponseStream(); 102.StreamReader sr = new StreamReader(s);103.104.//读取服务器端返回的消息105.String sReturnString = sr.ReadLine();106.s.Close();107.sr.Close();108.if (sReturnString == "Success")109.{110.returnValue = 1;111.}112.else if (sReturnString == "Error")113.{114.returnValue = 0;115.}116.117.}118.catch119.{120.returnValue = 0;121.}122.finally123.{124.fs.Close();125.r.Close();126.}127.128.return returnValue;129.}130.131.参数说明如下:132.133.address:接收文件的URL地址,如:http://localhost/UploadFile/Save.aspx134.135.fileNamePath:要上传的本地文件,如:D:/test.rar136.137.saveName:文件上传到服务器后的名称,如:200901011234.rar138.139.progressBar:显示文件上传进度的进度条。

winform利用webclient文件上传

winform利用webclient文件上传

此项目文件上传方案有:1:webclient 2:套接字3:嵌入bs模式利弊分析:方案一:利1利用http协议,避免了FTP协议传输的权限及端口配置2 利用URI 路径格式,便于项目操作弊1 不能断点续传2 速度比较慢 3 不能上传比较大的文件 4 不安全方案二:利端对端的传输,快、准。

弊文件路径不容易把握,对于项目的需求不是太符合。

方案三:这个方案的原来其实和利用webclient基本一样,这种方案做起来在cs模式里比较的繁琐。

项目文件上传利用webClient,原因如下:1:我们项目的所有利用的课件都比较的小,可以很好的避免的wenclient中的缺点。

2:项目在局域网里运行,基本可以不考虑安全问题。

(项目的服务端路径保存在数据库中)不过在我们调用C# WebClient类的实例对象前,我们需要用WebRequest类的对象发出对统一资源标识符(URI)的请求。

1.try2.{3.WebRequest myre=WebRequest.Create(URLAddress);4.}5.catch(WebException exp)6.{7.MessageBox.Show(exp.Message,"Error");8.}下面是上传文件的操作(修改了原有的许多Bug)1:浏览文件OpenFileDialog open = new OpenFileDialog();//根¨´据Y条¬?件t来¤¡ä判D断?文?件t类¤¨¤型¨ª(临¢¨´时º¡À条¬?件t)//opFile.Filter = "所¨´有®D文?档̦Ì(office、¡é视º¨®频¦Ì文?档̦Ì) |*.doc;*.ppt;*.xls;*.rmvb;*.MPG;*.AVI"; //判D断?文?件t格?式º?//FileInfo fileInfo = new FileInfo(opFile.FileName); //得Ì?到Ì?要°a上¦?传ä?的Ì?文?件t//int ss = Convert.ToInt32(fileInfo.Length) / (1024 * 1024); //文?件t大䨮小?MBif (open.ShowDialog() == System.Windows.Forms.DialogResult.OK){this.textBox1.Text = open.FileName;}2:上传文件(1)上传文件之前验证URI的有效性string URi = "http://192.168.0.222//wc/"; 这个路径是从UserInfo类中读取ServerAddress(这个在登录的时候读取赋值)WebRequest myWebRequest = WebRequest.Create(URi);myWebRequest.Timeout = -1;try{WebResponse webResponse = myWebRequest.GetResponse();Stream webStream = webResponse.GetResponseStream();webStream.Close();//开a始º?上¦?传ä?UploadFile(this.textBox1.Text, URi,true);}catch(WebException ex){if (ex.Status == WebExceptionStatus.ProtocolError){MessageBox.Show("服¤t务?器¡Â响¨¬应®|错䨪误¨®,ê?请?检¨¬查¨¦和¨ª服¤t务?器¡Â连¢?接¨®是º?否¤?正y常¡ê!ê?");}if (ex.Status == WebExceptionStatus.Timeout){MessageBox.Show("服¤t务?器¡Â超?时º¡À!ê?");}}(2)上传方法private void UploadFile(string fileNamePath, string uriString, bool IsAutoRename){//第̨²一°?步?:êo获?取¨?要°a上¦?传ä?的Ì?文?件t信?息¡éstring fileName = fileNamePath.Substring(stIndexOf("\\")+1); //获?取¨?上¦?传ä?文?件t名?称?string fileNameExt = fileName.Substring(stIndexOf(".") + 1).ToLower(); //文?件t后¨®缀Áo:êo小?写¡ästring newName = fileName;Guid gg = Guid.NewGuid();if (IsAutoRename == true){newName = gg.ToString() + fileName.Substring(stIndexOf(".")); //文?件t新?的Ì?名?称?}//第̨²二t部?:êo处ä|理¤¨ªURI地Ì?址¡¤if (uriString.EndsWith("/") == false){uriString = uriString + "/";}uriString = uriString + newName; //匹£¤配?要°a上¦?传ä?文?件t:êoURI+文?件t名?//第̨²三¨y部?:êo创ä¡ä建¡§wenClient实º¦Ì例¤yWebClient client = new WebClient();client.Credentials = CredentialCache.DefaultCredentials; //设¦¨¨置?进?行D身¦¨ª份¤Y验¨¦证¡è的Ì?网ª?络?凭?证¡è//第̨²四?部?:êo利¤?用®?流¢¡Â来¤¡ä实º¦Ì现?文?件t上¦?传ä?FileStream fs = new FileStream(fileNamePath, FileMode.Open, FileAccess.ReadWrite); //要°a上¦?传ä?的Ì?文?件t穿ä?件t文?件t流¢¡ÂBinaryReader br = new BinaryReader(fs); //以°?二t进?制?方¤?式º?读¨¢取¨?byte[] postArray = br.ReadBytes((int)fs.Length); //当Ì¡À前¡ã流¢¡Â写¡ä入¨?二t进?制?Stream postStream = client.OpenWrite(uriString, "PUT"); //向¨°指?定¡§的Ì?地Ì?址¡¤写¡ä入¨?数ºy据Ytry{if (postStream.CanWrite){postStream.Write(postArray, 0, postArray.Length);postStream.Close();fs.Dispose();MessageBox.Show("上¦?传ä?成¨¦功|!ê?");}else{postStream.Close();fs.Dispose();MessageBox.Show("上¦?传ä?失º¡ì败㨹!ê?");}}catch(Exception ex){postStream.Close();fs.Dispose();MessageBox.Show("上¦?传ä?文?件t异°¨¬常¡ê"+ex.Message);throw ex;}finally{postStream.Close();fs.Dispose();}}。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

在WinForm中通过HTTP协议向服务器端上传文件相信用写一个上传文件的网页大家都会写但是有没有人想过通过在WinForm中通过HTTP协议上传文件呢有些人说要向服务器端上传文件用FTP协议不是很简单吗效率又高为什么还要使用HTTP协议那么麻烦呢这里面有几个原因1FTP服务器的部署相对麻烦还要设置权限权限设置不对还会惹来一系列的安全问题。

2如果双方都还有防火墙又不想开发FTP相关的一些端口时HTTP就会大派用场就像WEB Services能穿透防火墙一样。

3其他的...还在想呢... 但是使用HTTP也有他的一些问题例如不能断点续传大文件上传很难速度很慢所以HTTP协议上传的文件大小不应该太大。

说了这么多原归正传一般来说在Winform里通过HTTP 上传文件有几种可选的方法1前面提到的Web Services就是一种很好的方法通过编写一个WebMethod包含有byte 类型的参数然后调用Web Services的方法文件内容就会以Base64编码传到服务器上然后重新保存即可。

WebMethod public void UploadFilebyte contentstring filename... Stream sw new StreamWriter... sw.Close 当然这种通过Base64编码的方法效率比较低那么可以采用WSE支持附件并以2进制形式传送效率会更高。

2除了通过WebService另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTP的POST动作来实现。

这时候首先需要编写一个web form来响应上传代码如下ltDOCTYPE HTML PUBLIC quot-//W3C//DTD HTML 4.0 Transitional//ENquot gt lthtmlgt ltheadgt lttitlegtWebForm1lt/titlegt ltmeta namequotGENERATORquot ContentquotMicrosoft Visual Studio .NET 7.1quotgt ltmetanamequotCODE_LANGUAGEquot ContentquotCquotgt ltmeta namequotvs_defaultClientScriptquot contentquotJavaScriptquotgt ltmetanamequotvs_targetSchemaquotcontentquot/intellisense/ie5quotgt lt/headgt ltbodygt ltform idquotForm1quot methodquotpostquot runatquotserverquotgt lt/formgt lt/bodygt lt/htmlgt using System using System.Collections using ponentModel using System.Data using System.Drawing using System.Web using System.Web.SessionState using System.Web.UI using System.Web.UI.WebControls usingSystem.Web.UI.HtmlControls namespace UploadFileWeb ...///// ltsummarygt /// WebForm1 的摘要说明。

/// lt/summarygt public class WebForm1 : System.Web.UI.Page ... private void Page_Loadobject sender System.EventArgs e ... // 在此处放置用户代码以初始化页面foreach string f inRequest.Files.AllKeys ... HttpPostedFile file Request.Filesffile.SaveAsquotD:Tempquot file.FileName ifRequest.ParamsquottestKeyquot null ...Response.WriteRequest.ParamsquottestKeyquot Web 窗体设计器生成的代码region Web 窗体设计器生成的代码override protected void OnInitEventArgs e ... // // CODEGEN: 该调用是 Web 窗体设计器所必需的。

// InitializeComponent base.OnInite ///// ltsummarygt /// 设计器支持所需的方法- 不要使用代码编辑器修改/// 此方法的内容。

/// lt/summarygt private void InitializeComponent ... this.Load new System.EventHandlerthis.Page_Load endregion 其实这个页面跟我们平常写的上传文件代码是一样的在Web 页的Request对象中包含有Files这个对象里面就包含了通过POST方式上传的所有文件的信息这时所需要做的就是调用Request.Filesi.SaveAs方法。

但是怎么让才能在WinForm里面模拟想Web Form POST 数据呢命名空间里面提供了两个非常有用的类一个是WebClient另外一个是HttpWebRequest类。

如果我们不需要通过代理服务器来上传文件那么非常简单只需要简单的调用WebClient.UploadFile方法就能实现上传文件private void button1_Clickobject sender System.EventArgs e ... WebClient myWebClient new WebClientmyWebClient.UploadFilequothttp://localhost/UploadFileWeb/WebForm1.aspx2222POST2222D:/Temp/Java/JavaStart/JavaSt art2.exequot 是不是觉得很简单呢确实就这么简单。

但是如果要通过代理服务器上传又怎么办呢那就需要使用到HttpWebRequest但是该类没有Upload方法但是幸运的是我们通过Reflector反编译了WebClient.UploadFile方法后我们发现其内部也是通过WebRequest来实现的代码如下public byte UploadFilestring address string method string fileName ... string text1 string text2 WebRequest request1 string text3 byte buffer1 byte buffer2 long num1 byte buffer3 int num2 WebResponse response1 byte buffer4 DateTime time1 long num3 string textArray1 FileStream stream1 null try ... fileName Path.GetFullPathfileName time1 DateTime.Now num3time1.Ticks text1 quot---------------------quotnum3.ToStringquotxquot if this.m_headers null ...this.m_headers new WebHeaderCollection text2this.m_headersquotContent-Typequot if text2 null ... iftext2.ToLowerCultureInfo.InvariantCulture.StartsWithquotmulti part/quot ... throw newWebExceptionSR.GetStringquotnet_webclient_Multipartquot else ... text2 quotapplication/octet-streamquotthis.m_headersquotContent-Typequot quotmultipart/form-data boundaryquot text1 this.m_responseHeaders null stream1 newFileStreamfileName FileMode.Open FileAccess.Read request1 WebRequest.Createthis.GetUriaddress request1.Credentials this.Credentials this.CopyHeadersTorequest1 request1.Method method textArray1 new string7 textArray10 quot--quot textArray11 text1 textArray12 quotrnContent-Disposition: form-data namequotfilequot filenamequotquot textArray13 Path.GetFileNamefileName textArray14 quotquotrnContent-Type: quot textArray15 text2 textArray16 quotrnrnquot text3 string.ConcattextArray1 buffer1 Encoding.UTF8.GetBytestext3 buffer2Encoding.ASCII.GetBytesquotrn--quot text1 quotrnquot num1 9223372036854775807 try ... num1 stream1.Lengthrequest1.ContentLength num1 long buffer1.Length longbuffer2.Length catch ... buffer3 new byteMath.Minint 8192 int num1 using Stream stream2 request1.GetRequestStream ... stream2.Writebuffer1 0 buffer1.Length do ... num2stream1.Readbuffer3 0 buffer3.Length if num2 0 ...stream2.Writebuffer3 0 num2 while num2 0stream2.Writebuffer2 0 buffer2.Length stream1.Close stream1 null response1 request1.GetResponse this.m_responseHeaders response1.Headers return this.ResponseAsBytesresponse1 catch Exception exception1 ... if stream1 null ... stream1.Closestream1 null if exception1 is WebException exception1 is SecurityException ... throw throw newWebExceptionSR.GetStringquotnet_webclientquot exception1 return buffer4 在这段代码里面其实最关键的就是如何模拟POST请求通过分析代码和监视HTTP我们可以发现模拟的POST格式如下-----------------------8c64f47716481f0 //时间戳Content-Disposition: form-data namequotfilequot filenamequota.txtquot //文件名Content-Type:application/octet-stream //文件的内容-----------------------8c64f47716481f0 这时候我们只需自己编码来模拟这么一组数据就行我们还可以好好借鉴MS的代码呢以下就是代码声明一下我是借用了别人的代码public class wwHttp ... ///// ltsummarygt /// Fires progress events when using GetUrlEvents to retrieve a URL. /// lt/summarygt public event OnReceiveDataHandler OnReceiveData ///// ltsummarygt /// Determines how data is POSTed when cPostBuffer is set. /// 1 - UrlEncoded /// 2 - Multi-Part form vars /// 4 - XML raw buffer content type: text/xml /// lt/summarygt public int PostMode ... get ... return this.nPostMode set ... this.nPostMode value ///// ltsummarygt /// User name used for Authentication. /// To use the currently logged in user when accessing an NTLM resource you can use quotAUTOLOGINquot. /// lt/summarygt publicstring Username ... get ... return this.cUsername set ... cUsername value ///// ltsummarygt /// Password for Authentication. /// lt/summarygt public string Password ...get ...return this.cPassword set ...this.cPassword value ///// ltsummarygt /// Address of the Proxy Server to be used. /// Use optional DEFAULTPROXY value to specify that you want to IEs Proxy Settings /// lt/summarygt public string ProxyAddress ... get ...return this.cProxyAddressset ...this.cProxyAddress value ///// ltsummarygt /// Semicolon separated Address list of the servers the proxy is not used for. /// lt/summarygt public string ProxyBypass ... get ...returnthis.cProxyBypass set ...this.cProxyBypass value ///// ltsummarygt /// Username for a password validating Proxy. Only used if the proxy info is set. /// lt/summarygt public string ProxyUsername ... get ...return this.cProxyUsernameset ...this.cProxyUsername value ///// ltsummarygt /// Password for a password validating Proxy. Only used if the proxy info is set. /// lt/summarygt public string ProxyPassword ... get ...return this.cProxyPassword set ...this.cProxyPassword value ///// ltsummarygt /// Timeout for the Web request in seconds. Times out on connection read and send operations. /// Default is 30 seconds. /// lt/summarygt public int Timeout ... get ...returnthis.nConnectTimeout set ...this.nConnectTimeout value ///// ltsummarygt /// Error Message if the Error Flag is set or an error value is returned from a method. /// lt/summarygt public string ErrorMsg ... get ... return this.cErrorMsg set ... this.cErrorMsg value ///// ltsummarygt /// Error flag if an error occurred. ///lt/summarygt public bool Error ... get ... return this.bError set ... this.bError value ///// ltsummarygt /// Determines whether errors cause exceptions to be thrown. By default errors /// are handled in the class and the Error property is set for error conditions. /// not implemented at this time. /// lt/summarygt public bool ThrowExceptions ... get ... return bThrowExceptions set ... this.bThrowExceptions value ///// ltsummarygt /// If set to anon-zero value will automatically track cookies. The number assigned is the cookie count. /// lt/summarygt public bool HandleCookies ... get ... return this.bHandleCookies set ... this.bHandleCookies value public CookieCollection Cookies ... get ... return this.oCookies set ... this.Cookies value public HttpWebResponse WebResponse ... get ... returnthis.oWebResponse set ... this.oWebResponse value public HttpWebRequest WebRequest ... get ... return this.oWebRequest set ... this.oWebRequest value // member properties //string cPostBuffer quotquot MemoryStream oPostStreamBinaryWriter oPostData int nPostMode 1 int nConnectTimeout 30 string cUserAgent quotWest Wind HTTP .NETquot string cUsername quotquot string cPassword quotquot string cProxyAddress quotquot string cProxyBypass quotquot string cProxyUsername quotquot string cProxyPassword quotquot bool bThrowExceptions false bool bHandleCookies false string cErrorMsg quotquot bool bError false HttpWebResponse oWebResponse HttpWebRequest oWebRequest CookieCollection oCookies string cMultiPartBoundaryquot-----------------------------7cf2a327f01aequot public void wwHTTP ... // // TODO: Add constructor logic here // ///// ltsummarygt /// Adds POST form variables to the request buffer. /// HttpPostMode determines how parms are handled. /// 1 - UrlEncoded Form Variables. Uses key and value pairs ie. quotNamequotquotRickquot to create URLEncoded content /// 2 - Multi-Part Forms - not supported /// 4 - XML block - Post a single XML block. Pass in as Key 1st Parm /// other - raw content buffer. Just assign to Key. /// lt/summarygt /// ltparam namequotKeyquotgtKey value or raw buffer depending on post typelt/paramgt /// ltparam namequotValuequotgtValue to store. Used only in key/value pair modeslt/paramgt public void AddPostKeystring Key byte Value ... if this.oPostData null ...this.oPostStream new MemoryStream this.oPostData new BinaryWriterthis.oPostStream if Key quotRESETquot ...this.oPostStream new MemoryStream this.oPostData new BinaryWriterthis.oPostStream switchthis.nPostMode ... case 1: this.oPostData.WriteEncoding.GetEncoding1252.GetBytes Key quotquot System.Web.HttpUtility.UrlEncodeValue quotampquot break case 2: this.oPostData.WriteEncoding.GetEncoding1252.GetBytes quot--quotthis.cMultiPartBoundary quotrnquot quotContent-Disposition: form-data namequotquot Keyquotquotrnrnquotthis.oPostData.Write Value this.oPostData.WriteEncoding.GetEncoding1252.GetBytesquotrnquot break default: this.oPostData.Write Value break public void AddPostKeystring Key string Value ...this.AddPostKeyKeyEncoding.GetEncoding1252.GetBytesValu e ///// ltsummarygt /// Adds a fully self contained POST buffer to the request. /// Works for XML or previously encoded content. /// lt/summarygt /// ltparamnamequotPostBufferquotgtlt/paramgt public void AddPostKeystring FullPostBuffer ... this.oPostData.Write Encoding.GetEncoding1252.GetBytesFullPostBuffer public bool AddPostFilestring Keystring FileName ... byte lcFile ifthis.nPostMode 2 ... this.cErrorMsg quotFile upload allowed only with Multi-part formsquot this.bError true return false try ... FileStream loFile newFileStreamFileNameSystem.IO.FileMode.OpenSystem.IO.FileA ccess.Read lcFile new byteloFile.Length loFile.ReadlcFile0int loFile.Length loFile.Close catchException e ... this.cErrorMsg e.Message this.bError true return false this.oPostData.Write Encoding.GetEncoding1252.GetBytes quot--quotthis.cMultiPartBoundary quotrnquot quotContent-Disposition: form-data namequotquot Key quotquot filenamequotquot new quotquotrnrnquot this.oPostData.Write lcFile this.oPostData.WriteEncoding.GetEncoding1252.GetBytesquotrnquot return true ///// ltsummarygt /// Return a the result from an HTTP Url into a StreamReader. /// Client code should call Close on the returned object when done reading. /// lt/summarygt /// ltparam namequotUrlquotgtUrl to retrieve.lt/paramgt /// ltparam namequotWebRequestquotgtAn HttpWebRequest object that can be passed in with properties preset.lt/paramgt /// ltreturnsgtlt/returnsgt protected StreamReader GetUrlStreamstring UrlHttpWebRequest Request ... try ... this.bError false this.cErrorMsg quotquot if Request null ...Request HttpWebRequest .WebRequest.CreateUrl erAgent this.cUserAgent Request.Timeoutthis.nConnectTimeout 1000 // Save for external accessthis.oWebRequest Request // Handle Security for the request if this.cUsername.Length gt 0 ... ifthis.cUsernamequotAUTOLOGINquot .。

相关文档
最新文档