Uploading files using WebClient and simultaneously post form data fields to the server

Source: Internet
Author: User
Tags allkeys http post

Before encountering a problem, is to use WebClient upload files at the same time, but also post form data field, the first thought that WebClient can be directly done, the results found that if the first post form field, you can only get fields and their values, if you first upload files, You can only get the contents of the uploaded file. It took a while to test that WebClient could not be used.

Google to the relevant solutions and classes, because the discovery of some articles on the internet is too simple to introduce is too complex, so here simply tidy up a bit, can help themselves to consolidate knowledge, but also hope to help everyone! If you do not understand anything, you can just leave a message to ask me.

About WebClient uploading files and simultaneously post form data implementation principle, we can refer to this article http://www.cnblogs.com/goody9807/archive/2007/06/06/773735.html, The descriptions are very detailed, but the classes and instances are somewhat blurry, so classes and instances can refer directly to this article.

Httprequestclient Class Code:
usingSystem;usingSystem.Collections;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.IO;usingSystem.Text;usingSystem.Net;namespacecommon.helper{/// <summary>  ///description:http POST Request client///last-modified-date:2012-02-28/// </summary>   Public classhttprequestclient {#region //Field    PrivateArrayList Bytesarray; PrivateEncoding Encoding =Encoding.UTF8; Private stringBoundary =String.Empty; #endregion     #region //Construction Method     Publichttprequestclient () {Bytesarray=NewArrayList (); stringFlag = DateTime.Now.Ticks.ToString ("x"); Boundary="---------------------------"+Flag; }    #endregion     #region //Method    /// <summary>    ///Merge request Data/// </summary>    /// <returns></returns>    Private byte[] mergecontent () {intLength =0; intReadlength =0; stringEndboundary ="--"+ Boundary +"--\r\n"; byte[] Endboundarybytes =encoding.       GetBytes (endboundary);       Bytesarray.add (endboundarybytes); foreach(byte[] BinchBytesarray) {Length+=b.length; }       byte[] bytes =New byte[length]; foreach(byte[] BinchBytesarray)        {b.copyto (bytes, readlength); Readlength+=b.length; }       returnbytes; }     /// <summary>    ///Upload/// </summary>    /// <param name= "Requesturl" >Request URL</param>    /// <param name= "ResponseText" >Response</param>    /// <returns></returns>     Public BOOLUpload (String Requesturl, outString ResponseText) {WebClient WebClient=NewWebClient (); WEBCLIENT.HEADERS.ADD ("Content-type","multipart/form-data; boundary="+boundary); byte[] responsebytes; byte[] bytes =mergecontent (); Try{responsebytes=webclient.uploaddata (Requesturl, bytes); ResponseText=System.Text.Encoding.UTF8.GetString (responsebytes); return true; }      Catch(WebException ex) {Stream Responsestream=Ex.        Response.getresponsestream (); ResponseBytes=New byte[Ex.        Response.contentlength]; Responsestream.read (ResponseBytes,0, responsebytes.length); } responsetext=System.Text.Encoding.UTF8.GetString (responsebytes); return false; }     /// <summary>    ///set up form data fields/// </summary>    /// <param name= "FieldName" >Field name</param>    /// <param name= "Fieldvalue" >field Value</param>    /// <returns></returns>     Public voidSetFieldValue (String fieldName, String fieldvalue) {stringHttprow ="--"+ Boundary +"\r\ncontent-disposition:form-data; name=\ "{0}\" \r\n\r\n{1}\r\n"; stringHttprowdata =String.Format (Httprow, FieldName, Fieldvalue); Bytesarray.add (encoding.    GetBytes (Httprowdata)); }     /// <summary>    ///set up form file data/// </summary>    /// <param name= "FieldName" >Field name</param>    /// <param name= "filename" >field Value</param>    /// <param name= "ContentType" >content inside Type</param>    /// <param name= "Filebytes" >file byte stream</param>    /// <returns></returns>     Public voidSetFieldValue (String fieldName, string filename, String contentType, byte[] filebytes) {stringEnd ="\ r \ n"; stringHttprow ="--"+ Boundary +"\r\ncontent-disposition:form-data; name=\ "{0}\"; filename=\ "{1}\" \r\ncontent-type: {2}\r\n\r\n"; stringHttprowdata =String.Format (Httprow, fieldName, filename, contentType); byte[] Headerbytes =encoding.      GetBytes (Httprowdata); byte[] Endbytes =encoding.      GetBytes (end); byte[] Filedatabytes =New byte[Headerbytes.length + Filebytes.length +Endbytes.length]; Headerbytes.copyto (Filedatabytes,0);      Filebytes.copyto (Filedatabytes, headerbytes.length); Endbytes.copyto (filedatabytes, Headerbytes.length+filebytes.length);    Bytesarray.add (filedatabytes); }    #endregion  }}
Client Instance code:
stringFilefullname=@"C:\test.txt", filedvalue="Hello_world", ResponseText =""; FileStream FS=NewFileStream (Filefullname, System.IO.FileMode.Open, System.IO.FileAccess.Read);byte[] Filebytes =New byte[FS. Length];fs. Read (Filebytes,0, Filebytes.length); fs. Close (); Fs. Dispose (); Httprequestclient httprequestclient=Newhttprequestclient (); Httprequestclient.setfieldvalue ("Key", Filedvalue); Httprequestclient.setfieldvalue ("UploadFile", Path.getfilename (Filefullname),"Application/octet-stream", filebytes); Httprequestclient.upload (NormalBotConfig.Instance.GetUploadFileUrl (), outResponseText);
Server-side Instance code:
if(HttpContext.Current.Request.Files.AllKeys.Length >0){  stringFilePath = Path.Combine (HttpContext.Current.Server.MapPath ("~/"),"UploadFile", DateTime.Now.Year.ToString (), DateTime.Now.Month.ToString (), DateTime.Now.Day.ToString ()); if(!directory.exists (FilePath))  Directory.CreateDirectory (FilePath); //here I directly use the index to get the first file, if uploading more than one file, you can traverse HttpContext.Current.Request.Files.AllKeys to take "key value", Get the file again by httpcontext.current.request.files["key value"]httpcontext.current.request.files[0]. SaveAs (Path.Combine (FilePath, httpcontext.current.request.files[0].  FileName)); stringFiledvalue = httpcontext.current.request.form["Key"];}

Ext.: http://www.97world.com/archives/2963#

Uploading files using WebClient and simultaneously post form data fields to the server

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.