欢迎来到三一文库! | 帮助中心 三一文库31doc.com 一个上传文档投稿赚钱的网站
三一文库
全部分类
  • 研究报告>
  • 工作总结>
  • 合同范本>
  • 心得体会>
  • 工作报告>
  • 党团相关>
  • 幼儿/小学教育>
  • 高等教育>
  • 经济/贸易/财会>
  • 建筑/环境>
  • 金融/证券>
  • 医学/心理学>
  • ImageVerifierCode 换一换
    首页 三一文库 > 资源分类 > PDF文档下载  

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

    • 资源ID:4736450       资源大小:67.37KB        全文页数:12页
    • 资源格式: PDF        下载积分:4
    快捷下载 游客一键下载
    会员登录下载
    微信登录下载
    三方登录下载: 微信开放平台登录 QQ登录   微博登录  
    二维码
    微信扫一扫登录
    下载资源需要4
    邮箱/手机:
    温馨提示:
    用户名和密码都是您填写的邮箱或者手机号,方便查询和重复下载(系统自动生成)
    支付方式: 支付宝    微信支付   
    验证码:   换一换

    加入VIP免费专享
     
    账号:
    密码:
    验证码:   换一换
      忘记密码?
        
    友情提示
    2、PDF文件下载后,可能会被浏览器默认打开,此种情况可以点击浏览器菜单,保存网页到桌面,就可以正常下载了。
    3、本站不支持迅雷下载,请使用电脑自带的IE浏览器,或者360浏览器、谷歌浏览器下载即可。
    4、本站资源下载后的文档和图纸-无水印,预览文档经过压缩,下载后原文更清晰。
    5、试题试卷类文档,如果标题没有明确说明有答案则都视为没有答案,请知晓。

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

    在 WinForm 中通过 HTTP 协议向服务器端上传文件相信 用 ASP.NET 写一个上传文件的网页大家都会写但是有没有 人想过通过在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 动作来实现。这时候首先需要编写一个asp.net 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 ltmeta namequotCODE_LANGUAGEquot ContentquotCquotgt ltmeta namequotvs_defaultClientScriptquot contentquotJavaScriptquotgt ltmeta namequotvs_targetSchemaquot contentquothttp:/schemas.microsoft.com/intellisense/ie5quotgt lt/headgt ltbodygt ltform idquotForm1quot methodquotpostquot runatquotserverquotgt lt/formgt lt/bodygt lt/htmlgt using System using System.Collections using System.ComponentModel 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 . / ltsummarygt / WebForm1 的摘要说明。/ lt/summarygt public class WebForm1 : System.Web.UI.Page . private void Page_Loadobject sender System.EventArgs e . / 在此处放置 用户代码以初始化页面foreach string f in Request.Files.AllKeys . HttpPostedFile file Request.Filesf file.SaveAsquotD:Tempquot file.FileName if Request.ParamsquottestKeyquot null . Response.WriteRequest.ParamsquottestKeyquot Web 窗体设 计器生成的代码region Web 窗体设计器生成的代码 override protected void OnInitEventArgs e . / / CODEGEN: 该调用是ASP.NET Web 窗体设计器所必需的。/ InitializeComponent base.OnInite / ltsummarygt / 设计器 支持所需的方法- 不要使用代码编辑器修改/ 此方法的 内容。/ lt/summarygt private void InitializeComponent . this.Load new System.EventHandlerthis.Page_Load endregion 其实这个页面跟我们平常写的asp.net上传文件代码是一样 的在 Web 页的 Request对象中包含有Files 这个对象里面就 包含了通过POST 方式上传的所有文件的信息这时所需要做 的就是调用Request.Filesi.SaveAs 方法。 但是怎么让才能在 WinForm 里面模拟想Web Form POST 数据呢 System.Net 命 名空间里面提供了两个非常有用的类一个是WebClient 另外 一个是 HttpWebRequest 类。 如果我们不需要通过代理服务器 来上传文件那么非常简单只需要简单的调用 WebClient.UploadFile 方法就能实现上传文件private void button1_Clickobject sender System.EventArgs e . WebClient myWebClient new WebClient myWebClient.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 num3 time1.Ticks text1 quot-quot num3.ToStringquotxquot if this.m_headers null . this.m_headers new WebHeaderCollection text2 this.m_headersquotContent-Typequot if text2 null . if text2.ToLowerCultureInfo.InvariantCulture.StartsWithquotmulti part/quot . throw new WebExceptionSR.GetStringquotnet_webclient_Multipartquot else . text2 quotapplication/octet-streamquot this.m_headersquotContent-Typequot quotmultipart/form-data boundaryquot text1 this.m_responseHeaders null stream1 new FileStreamfileName 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 buffer2 Encoding.ASCII.GetBytesquotrn-quot text1 quotrnquot num1 9223372036854775807 try . num1 stream1.Length request1.ContentLength num1 long buffer1.Length long buffer2.Length catch . buffer3 new byteMath.Minint 8192 int num1 using Stream stream2 request1.GetRequestStream . stream2.Writebuffer1 0 buffer1.Length do . num2 stream1.Readbuffer3 0 buffer3.Length if num2 0 . stream2.Writebuffer3 0 num2 while num2 0 stream2.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.Close stream1 null if exception1 is WebException exception1 is SecurityException . throw throw new WebExceptionSR.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 public string 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.cProxyAddress set .this.cProxyAddress value / ltsummarygt / Semicolon separated Address list of the servers the proxy is not used for. / lt/summarygt public string ProxyBypass . get .return this.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.cProxyUsername set .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 .return this.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 a non-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 . return this.oWebResponse set . this.oWebResponse value public HttpWebRequest WebRequest . get . return this.oWebRequest set . this.oWebRequest value / member properties /string cPostBuffer quotquot MemoryStream oPostStream BinaryWriter 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 cMultiPartBoundary quot-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.Write Encoding.GetEncoding1252.GetBytes quot-quot this.cMultiPartBoundary quotrnquot quotContent-Disposition: form-data namequotquot Keyquotquotrnrnquot this.oPostData.Write Value this.oPostData.Write Encoding.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 / ltparam namequotPostBufferquotgtlt/paramgt public void AddPostKeystring FullPostBuffer . this.oPostData.Write Encoding.GetEncoding1252.GetBytesFullPostBuffer public bool AddPostFilestring Keystring FileName . byte lcFile if this.nPostMode 2 . this.cErrorMsg quotFile upload allowed only with Multi-part formsquot this.bError true return false try . FileStream loFile new FileStreamFileNameSystem.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-quot this.cMultiPartBoundary quotrnquot quotContent-Disposition: form-data namequotquot Key quotquot filenamequotquot new FileInfoFileName.Name quotquotrnrnquot this.oPostData.Write lcFile this.oPostData.Write Encoding.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 System.Net.WebRequest.CreateUrl Request.UserAgent this.cUserAgent Request.Timeout this.nConnectTimeout 1000 / Save for external access this.oWebRequest Request / Handle Security for the request if this.cUsername.Length gt 0 . if this.cUsernamequotAUTOLOGINquot .

    注意事项

    本文(在WinForm中通过HTTP协议向服务器端上传文件.pdf)为本站会员(tbuqq)主动上传,三一文库仅提供信息存储空间,仅对用户上传内容的表现方式做保护处理,对上载内容本身不做任何修改或编辑。 若此文所含内容侵犯了您的版权或隐私,请立即通知三一文库(点击联系客服),我们立即给予删除!

    温馨提示:如果因为网速或其他原因下载失败请重新下载,重复下载不扣分。




    经营许可证编号:宁ICP备18001539号-1

    三一文库
    收起
    展开