C # analog multi-File upload

Source: Internet
Author: User

Original address: http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html

1, the client code is written with WinForm

Private voidButton1_Click (Objectsender, EventArgs e) {    stringPostURL ="http://localhost:40694/test1/Handler1.ashx"; string[] files = {"F:\\1.png","F:\\2.png" }; stringstr =httpuploadfile (posturl, files); MessageBox.Show (str);} Public stringHttpuploadfile (stringUrlstring[] files) {    //HttpContext context//refer to http://www.cnblogs.com/greenerycn/archive/2010/05/15/csharp_http_post.html    varMemstream =NewMemoryStream (); //Boundary character    varBoundary ="---------------"+ DateTime.Now.Ticks.ToString ("x"); varBeginboundary = Encoding.ASCII.GetBytes ("--"+ Boundary +"\ r \ n"); //File parameter Header    foreach(varIteminchfiles) {        stringFilePath =item; stringFileName =path.getfilename (item); varFileStream =NewFileStream (FilePath, FileMode.Open, FileAccess.Read); varFileheaderbytes = Encoding.UTF8.GetBytes ($"content-disposition:form-data; name=\ "{"File"}\"; Filename=\ "{filename}\" \r\ncontent-type:application/octet-stream\r\n\r\n"); //Start spelling DataMemstream.write (Beginboundary,0, beginboundary.length); //File DataMemstream.write (Fileheaderbytes,0, fileheaderbytes.length); varBuffer =New byte[1024x768]; intBytesread;  while(Bytesread = filestream.read (buffer,0, buffer. Length))! =0) {memstream.write (buffer,0, Bytesread);        } filestream.close (); //you have to write a newline.        byte[] bytes = Encoding.UTF8.GetBytes ($"\ r \ n"); Memstream.write (Bytes,0, Bytes.    Length); }    ////Key-value Data    //dictionary<string, string> stringdict = new dictionary<string, string> (); //Stringdict.add ("Len", "500"); //Stringdict.add ("Wid", "300"); //Stringdict.add ("Test1", "1"); //foreach (var item in stringdict)//{    //String name = Item.    Key; //String value = Item.    Value; //byte[] bytes = Encoding.UTF8.GetBytes ($ "\r\n--{boundary}\r\ncontent-disposition:form-data; name=\" {name}\ "\r\    N\r\n{value}\r\n "); //memstream.write (bytes, 0, bytes.    Length); //}    //writes the last end of the bounding character    varEndboundary = Encoding.ASCII.GetBytes ("--"+ Boundary +"--\r\n");//the last TerminatorMemstream.write (Endboundary,0, endboundary.length); //Write to TempbufferMemstream.position =0; varTempbuffer =New byte[Memstream.length]; Memstream.read (Tempbuffer,0, tempbuffer.length);    Memstream.close (); //create WebRequest and set properties    varWebRequest =(HttpWebRequest) webrequest.create (URL); Webrequest.method="POST"; Webrequest.timeout=100000; Webrequest.contenttype="multipart/form-data; boundary="+boundary; Webrequest.contentlength=tempbuffer.length; varRequeststream =Webrequest.getrequeststream (); requestStream.Write (Tempbuffer,0, tempbuffer.length);    Requeststream.close (); varHttpWebResponse =(HttpWebResponse) webrequest.getresponse (); stringresponsecontent; using(varHttpstreamreader =NewStreamReader (Httpwebresponse.getresponsestream (), Encoding.GetEncoding ("Utf-8")) {responsecontent=Httpstreamreader.readtoend ();    } httpwebresponse.close ();    Webrequest.abort (); returnresponsecontent;}

2. Service-side code

  Public classHandler1:ihttphandler { Public voidProcessRequest (HttpContext context) {context. Response.ContentType="Text/plain"; stringStrfilenames =""; if(Context. Request.Files.Count >0)            {                 for(inti =0; I < context. Request.Files.Count; i++) {Httppostedfile _httppostedfile=context.                    Request.files[i]; Strfilenames+ = _httppostedfile.filename +","; _httppostedfile.saveas (context. Server.MapPath ($"./{_httppostedfile.filename}")); }                //context. Response.Write ($ "files:{context. Request.Files.Count} filenames:{strfilenames} ");            }            //context. Response.Write (context.            request.form["Len"]); //context. Response.Write (Jsonconvert.serializeobject) (context. Request.Form.AllKeys.Length.ToString ()));context.        Response.Write (Strfilenames); }         Public BOOLisreusable {Get            {                return false; }        }    }

C # analog multi-File upload

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.