在WinForm中通过HTTP协议向服务器端上传文件
本作品内容为在WinForm中通过HTTP协议向服务器端上传文件,格式为 doc ,大小 43520 KB ,页数为 14页
('在WinForm中通过HTTP协议向服务器端上传文件相信用ASP.NET写一个上传文件的网页大家都会写但是有没有人想过通过在WinForm中通过HTTP协议上传文件呢有些人说要向服务器端上传文件用FTP协议不是很简单吗效率又高为什么还要使用HTTP协议那么麻烦呢这里面有几个原因1FTP服务器的部署相对麻烦还要设置权限权限设置不对还会惹来一系列的安全问题。2如果双方都还有防火墙又不想开发FTP相关的一些端口时HTTP就会大派用场就像WEBServices能穿透防火墙一样。3其他的...还在想呢...但是使用HTTP也有他的一些问题例如不能断点续传大文件上传很难速度很慢所以HTTP协议上传的文件大小不应该太大。说了这么多原归正传一般来说在Winform里通过HTTP上传文件有几种可选的方法1前面提到的WebServices就是一种很好的方法通过编写一个WebMethod包含有byte类型的参数然后调用WebServices的方法文件内容就会以Base64编码传到服务器上然后重新保存即可。WebMethodpublicvoidUploadFilebytecontentstringfilename...StreamswnewStreamWriter...sw.Close当然这种通过Base64编码的方法效率比较低那么可以采用WSE支持附件并以2进制形式传送效率会更高。2除了通过WebService另外一种更简单的方法就是通过WebClient或者HttpWebRequest来模拟HTTP的POST动作来实现。这时候首先需要编写一个asp.netwebform来响应上传代码如下ltDOCTYPEHTMLPUBLICquot-//W3C//DTDHTML4.0Transitional//ENquotgtlthtmlgtltheadgtlttitlegtWebForm1lt/titlegtltmetanamequotGENERATORquotContentquotMicrosoftVisualStudio.NET7.1quotgtltmetanamequotCODE_LANGUAGEquotContentquotCquotgtltmetanamequotvs_defaultClientScriptquotcontentquotJavaScriptquotgtltmetanamequotvs_targetSchemaquotcontentquothttp://schemas.microsoft.com/intellisense/ie5quotgtlt/headgtltbodygtltformidquotForm1quotmethodquotpostquotrunatquotserverquotgtlt/formgtlt/bodygtlt/htmlgtusingSystemusingSystem.CollectionsusingSystem.ComponentModelusingSystem.DatausingSystem.DrawingusingSystem.WebusingSystem.Web.SessionStateusingSystem.Web.UIusingSystem.Web.UI.WebControlsusingSystem.Web.UI.HtmlControlsnamespaceUploadFileWeb.../////ltsummarygt///WebForm1的摘要说明。///lt/summarygtpublicclassWebForm1:System.Web.UI.Page...privatevoidPage_LoadobjectsenderSystem.EventArgse...//在此处放置用户代码以初始化页面foreachstringfinRequest.Files.AllKeys...HttpPostedFilefileRequest.Filesffile.SaveAsquotD:Tempquotfile.FileNameifRequest.ParamsquottestKeyquotnull...Response.WriteRequest.ParamsquottestKeyquotWeb窗体设计器生成的代码regionWeb窗体设计器生成的代码overrideprotectedvoidOnInitEventArgse...////CODEGEN:该调用是ASP.NETWeb窗体设计器所必需的。//InitializeComponentbase.OnInite/////ltsummarygt///设计器支持所需的方法-不要使用代码编辑器修改///此方法的内容。///lt/summarygtprivatevoidInitializeComponent...this.LoadnewSystem.EventHandlerthis.Page_Loadendregion其实这个页面跟我们平常写的asp.net上传文件代码是一样的在Web页的Request对象中包含有Files这个对象里面就包含了通过POST方式上传的所有文件的信息这时所需要做的就是调用Request.Filesi.SaveAs方法。但是怎么让才能在WinForm里面模拟想WebFormPOST数据呢System.Net命名空间里面提供了两个非常有用的类一个是WebClient另外一个是HttpWebRequest类。如果我们不需要通过代理服务器来上传文件那么非常简单只需要简单的调用WebClient.UploadFile方法就能实现上传文件privatevoidbutton1_ClickobjectsenderSystem.EventArgse...WebClientmyWebClientnewWebClientmyWebClient.UploadFilequothttp://localhost/UploadFileWeb/WebForm1.aspx2222POST2222D:/Temp/Java/JavaStart/JavaStart2.exequot是不是觉得很简单呢确实就这么简单。但是如果要通过代理服务器上传又怎么办呢那就需要使用到HttpWebRequest但是该类没有Upload方法但是幸运的是我们通过Reflector反编译了WebClient.UploadFile方法后我们发现其内部也是通过WebRequest来实现的代码如下publicbyteUploadFilestringaddressstringmethodstringfileName...stringtext1stringtext2WebRequestrequest1stringtext3bytebuffer1bytebuffer2longnum1bytebuffer3intnum2WebResponseresponse1bytebuffer4DateTimetime1longnum3stringtextArray1FileStreamstream1nulltry...fileNamePath.GetFullPathfileNametime1DateTime.Nownum3time1.Tickstext1quot---------------------quotnum3.ToStringquotxquotifthis.m_headersnull...this.m_headersnewWebHeaderCollectiontext2this.m_headersquotContent-Typequotiftext2null...iftext2.ToLowerCultureInfo.InvariantCulture.StartsWithquotmultipart/quot...thrownewWebExceptionSR.GetStringquotnet_webclient_Multipartquotelse...text2quotapplication/octet-streamquotthis.m_headersquotContent-Typequotquotmultipart/form-databoundaryquottext1this.m_responseHeadersnullstream1newFileStreamfileNameFileMode.OpenFileAccess.Readrequest1WebRequest.Createthis.GetUriaddressrequest1.Credentialsthis.Credentialsthis.CopyHeadersTorequest1request1.MethodmethodtextArray1newstring7textArray10quot--quottextArray11text1textArray12quotrnContent-Disposition:form-datanamequotfilequotfilenamequotquottextArray13Path.GetFileNamefileNametextArray14quotquotrnContent-Type:quottextArray15text2textArray16quotrnrnquottext3string.ConcattextArray1buffer1Encoding.UTF8.GetBytestext3buffer2Encoding.ASCII.GetBytesquotrn--quottext1quotrnquotnum19223372036854775807try...num1stream1.Lengthrequest1.ContentLengthnum1longbuffer1.Lengthlongbuffer2.Lengthcatch...buffer3newbyteMath.Minint8192intnum1usingStreamstream2request1.GetRequestStream...stream2.Writebuffer10buffer1.Lengthdo...num2stream1.Readbuffer30buffer3.Lengthifnum20...stream2.Writebuffer30num2whilenum20stream2.Writebuffer20buffer2.Lengthstream1.Closestream1nullresponse1request1.GetResponsethis.m_responseHeadersresponse1.Headersreturnthis.ResponseAsBytesresponse1catchExceptionexception1...ifstream1null...stream1.Closestream1nullifexception1isWebExceptionexception1isSecurityException...throwthrownewWebExceptionSR.GetStringquotnet_webclientquotexception1returnbuffer4在这段代码里面其实最关键的就是如何模拟POST请求通过分析代码和监视HTTP我们可以发现模拟的POST格式如下-----------------------8c64f47716481f0//时间戳Content-Disposition:form-datanamequotfilequotfilenamequota.txtquot//文件名Content-Type:application/octet-stream//文件的内容-----------------------8c64f47716481f0这时候我们只需自己编码来模拟这么一组数据就行我们还可以好好借鉴MS的代码呢以下就是代码声明一下我是借用了别人的代码publicclasswwHttp.../////ltsummarygt///FiresprogresseventswhenusingGetUrlEventstoretrieveaURL.///lt/summarygtpubliceventOnReceiveDataHandlerOnReceiveData/////ltsummarygt///DetermineshowdataisPOSTedwhencPostBufferisset.///1-UrlEncoded///2-Multi-Partformvars///4-XMLrawbuffercontenttype:text/xml///lt/summarygtpublicintPostMode...get...returnthis.nPostModeset...this.nPostModevalue/////ltsummarygt///UsernameusedforAuthentication.///TousethecurrentlyloggedinuserwhenaccessinganNTLMresourceyoucanusequotAUTOLOGINquot.///lt/summarygtpublicstringUsername...get...returnthis.cUsernameset...cUsernamevalue/////ltsummarygt///PasswordforAuthentication.///lt/summarygtpublicstringPassword...get...returnthis.cPasswordset...this.cPasswordvalue/////ltsummarygt///AddressoftheProxyServertobeused.///UseoptionalDEFAULTPROXYvaluetospecifythatyouwanttoIEsProxySettings///lt/summarygtpublicstringProxyAddress...get...returnthis.cProxyAddressset...this.cProxyAddressvalue/////ltsummarygt///SemicolonseparatedAddresslistoftheserverstheproxyisnotusedfor.///lt/summarygtpublicstringProxyBypass...get...returnthis.cProxyBypassset...this.cProxyBypassvalue/////ltsummarygt///UsernameforapasswordvalidatingProxy.Onlyusediftheproxyinfoisset.///lt/summarygtpublicstringProxyUsername...get...returnthis.cProxyUsernameset...this.cProxyUsernamevalue/////ltsummarygt///PasswordforapasswordvalidatingProxy.Onlyusediftheproxyinfoisset.///lt/summarygtpublicstringProxyPassword...get...returnthis.cProxyPasswordset...this.cProxyPasswordvalue/////ltsummarygt///TimeoutfortheWebrequestinseconds.Timesoutonconnectionreadandsendoperations.///Defaultis30seconds.///lt/summarygtpublicintTimeout...get...returnthis.nConnectTimeoutset...this.nConnectTimeoutvalue/////ltsummarygt///ErrorMessageiftheErrorFlagissetoranerrorvalueisreturnedfromamethod.///lt/summarygtpublicstringErrorMsg...get...returnthis.cErrorMsgset...this.cErrorMsgvalue/////ltsummarygt///Errorflagifanerroroccurred.///lt/summarygtpublicboolError...get...returnthis.bErrorset...this.bErrorvalue/////ltsummarygt///Determineswhethererrorscauseexceptionstobethrown.Bydefaulterrors///arehandledintheclassandtheErrorpropertyissetforerrorconditions.///notimplementedatthistime.///lt/summarygtpublicboolThrowExceptions...get...returnbThrowExceptionsset...this.bThrowExceptionsvalue/////ltsummarygt///Ifsettoanon-zerovaluewillautomaticallytrackcookies.Thenumberassignedisthecookiecount.///lt/summarygtpublicboolHandleCookies...get...returnthis.bHandleCookiesset...this.bHandleCookiesvaluepublicCookieCollectionCookies...get...returnthis.oCookiesset...this.CookiesvaluepublicHttpWebResponseWebResponse...get...returnthis.oWebResponseset...this.oWebResponsevaluepublicHttpWebRequestWebRequest...get...returnthis.oWebRequestset...this.oWebRequestvalue//memberproperties//stringcPostBufferquotquotMemoryStreamoPostStreamBinaryWriteroPostDataintnPostMode1intnConnectTimeout30stringcUserAgentquotWestWindHTTP.NETquotstringcUsernamequotquotstringcPasswordquotquotstringcProxyAddressquotquotstringcProxyBypassquotquotstringcProxyUsernamequotquotstringcProxyPasswordquotquotboolbThrowExceptionsfalseboolbHandleCookiesfalsestringcErrorMsgquotquotboolbErrorfalseHttpWebResponseoWebResponseHttpWebRequestoWebRequestCookieCollectionoCookiesstringcMultiPartBoundaryquot-----------------------------7cf2a327f01aequotpublicvoidwwHTTP...////TODO:Addconstructorlogichere///////ltsummarygt///AddsPOSTformvariablestotherequestbuffer.///HttpPostModedetermineshowparmsarehandled.///1-UrlEncodedFormVariables.Useskeyandvaluepairsie.quotNamequotquotRickquottocreateURLEncodedcontent///2-Multi-PartForms-notsupported///4-XMLblock-PostasingleXMLblock.PassinasKey1stParm///other-rawcontentbuffer.JustassigntoKey.///lt/summarygt///ltparamnamequotKeyquotgtKeyvalueorrawbufferdependingonposttypelt/paramgt///ltparamnamequotValuequotgtValuetostore.Usedonlyinkey/valuepairmodeslt/paramgtpublicvoidAddPostKeystringKeybyteValue...ifthis.oPostDatanull...this.oPostStreamnewMemoryStreamthis.oPostDatanewBinaryWriterthis.oPostStreamifKeyquotRESETquot...this.oPostStreamnewMemoryStreamthis.oPostDatanewBinaryWriterthis.oPostStreamswitchthis.nPostMode...case1:this.oPostData.WriteEncoding.GetEncoding1252.GetBytesKeyquotquotSystem.Web.HttpUtility.UrlEncodeValuequotampquotbreakcase2:this.oPostData.WriteEncoding.GetEncoding1252.GetBytesquot--quotthis.cMultiPartBoundaryquotrnquotquotContent-Disposition:form-datanamequotquotKeyquotquotrnrnquotthis.oPostData.WriteValuethis.oPostData.WriteEncoding.GetEncoding1252.GetBytesquotrnquotbreakdefault:this.oPostData.WriteValuebreakpublicvoidAddPostKeystringKeystringValue...this.AddPostKeyKeyEncoding.GetEncoding1252.GetBytesValue/////ltsummarygt///AddsafullyselfcontainedPOSTbuffertotherequest.///WorksforXMLorpreviouslyencodedcontent.///lt/summarygt///ltparamnamequotPostBufferquotgtlt/paramgtpublicvoidAddPostKeystringFullPostBuffer...this.oPostData.WriteEncoding.GetEncoding1252.GetBytesFullPostBufferpublicboolAddPostFilestringKeystringFileName...bytelcFileifthis.nPostMode2...this.cErrorMsgquotFileuploadallowedonlywithMulti-partformsquotthis.bErrortruereturnfalsetry...FileStreamloFilenewFileStreamFileNameSystem.IO.FileMode.OpenSystem.IO.FileAccess.ReadlcFilenewbyteloFile.LengthloFile.ReadlcFile0intloFile.LengthloFile.ClosecatchExceptione...this.cErrorMsge.Messagethis.bErrortruereturnfalsethis.oPostData.WriteEncoding.GetEncoding1252.GetBytesquot--quotthis.cMultiPartBoundaryquotrnquotquotContent-Disposition:form-datanamequotquotKeyquotquotfilenamequotquotnewFileInfoFileName.Namequotquotrnrnquotthis.oPostData.WritelcFilethis.oPostData.WriteEncoding.GetEncoding1252.GetBytesquotrnquotreturntrue/////ltsummarygt///ReturnatheresultfromanHTTPUrlintoaStreamReader.///ClientcodeshouldcallCloseonthereturnedobjectwhendonereading.///lt/summarygt///ltparamnamequotUrlquotgtUrltoretrieve.lt/paramgt///ltparamnamequotWebRequestquotgtAnHttpWebRequestobjectthatcanbepassedinwithpropertiespreset.lt/paramgt///ltreturnsgtlt/returnsgtprotectedStreamReaderGetUrlStreamstringUrlHttpWebRequestRequest...try...this.bErrorfalsethis.cErrorMsgquotquotifRequestnull...RequestHttpWebRequestSystem.Net.WebRequest.CreateUrlRequest.UserAgentthis.cUserAgentRequest.Timeoutthis.nConnectTimeout1000//Saveforexternalaccessthis.oWebRequestRequest//HandleSecurityfortherequestifthis.cUsername.Lengthgt0...ifthis.cUsernamequotAUTOLOGINquot.',)
提供在WinForm中通过HTTP协议向服务器端上传文件会员下载,编号:1700668343,格式为 docx,文件大小为14页,请使用软件:wps,office word 进行编辑,PPT模板中文字,图片,动画效果均可修改,PPT模板下载后图片无水印,更多精品PPT素材下载尽在某某PPT网。所有作品均是用户自行上传分享并拥有版权或使用权,仅供网友学习交流,未经上传用户书面授权,请勿作他用。若您的权利被侵害,请联系963098962@qq.com进行删除处理。