C # Post text picture to server

Source: Internet
Author: User

Ching

Original address: http://blog.csdn.net/qingdujun/article/details/41764521


Recently, because the project needs to implement C # submit text and data to the server, so the study of C # PHP data transfer;

Below is an example to demonstrate, C # post text + picture, PHP side receive;


Post submission Data core code (post data submission)

Using system;using system.collections.generic;using system.linq;using system.text;using System.IO;using        System.drawing;using system.web;using System.net;namespace postpic{class Postclass {//<summary> Post text and pictures to the server///</summary>//<param name= "url" >url</param>//<para M name= "UserName" > User name </param>//<param name= "userpwd" > Password </param>//<param name= " Jpegpath "> Avatar address </param>//<returns> return server return value </returns> public string post (string url,st Ring UserName, String userpwd, String jpegpath) {//Convert picture to byte[] and convert to string string array = Con Vert.            ToBase64String (ImageToByteArray (Jpegpath));                  Constructs the post submission field string para = "name=" +username+ "&pwd=" +userpwd+ "&head=" +httputility.urlencode (array); #region HttpWebRequest notation HttpWebRequest httpweb = (HttpWebRequest) webrequest.creAte (URL);            Httpweb.timeout = 20000;            Httpweb.method = "POST";            Httpweb.contenttype = "application/x-www-form-urlencoded";            byte[] Bytepara = Encoding.ASCII.GetBytes (para); using (Stream Reqstream = Httpweb.getrequeststream ()) {//Submit data Reqstream.write (by Tepara, 0, para.            Length);            }//Get server return value HttpWebResponse HttpWebResponse = (HttpWebResponse) httpweb.getresponse ();            Stream stream = Httpwebresponse.getresponsestream ();            StreamReader StreamReader = new StreamReader (Stream, encoding.getencoding ("Utf-8"));            Gets the return value of string result = Streamreader.readtoend (); Stream.            Close ();        #endregion//Returns the return value of the server to return result; }///<summary>//image to Byte byte array///</summary>//<param name= "FilePath" > Road Diameter </param>///<returns> byte array </Returns> Private byte[] ImageToByteArray (string FilePath) {using (MemoryStream ms = new Memor                    Ystream ()) {using (Image ImageIn = Image.FromFile (FilePath)) { using (Bitmap BMP = new Bitmap (ImageIn)) {BMP.                    Save (MS, Imagein.rawformat); }} return Ms.            ToArray (); }        }    }    }

One, C # client

To make it easier to explain, I simply simplified, and a submit button was just fine.



Second, the need to submit pictures

The picture is stored in my e-packing directory under the ~~~~~ (paste a random picture)

Path = @ "E:\head.jpg";



Third, PHP service side

After receiving the image, store it to, Path = @ "C:\Login\log";


Appendix:

C # side code:

C # Interface Simple code ~~~~~ (this code can be skipped ~~~~~)

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing;    Using system.linq;using system.text;using system.windows.forms;namespace postpic{public partial class Postfrom:form        {public Postfrom () {InitializeComponent (); }///<summary>///Submit the Post data///</summary>//<param name= "Sender" &GT;&L         t;/param>//<param name= "E" ></param> private void Btnpost_click (object sender, EventArgs e)            {//postclass for Data submission class Postclass PS = new Postclass ();            String url = @ "http://localhost/login.php";            String name = "DOOZN";            string pwd = "a12345";            String jpegpath = @ "E:\head.jpg";            Commit data String value = Ps.post (Url,name,pwd,jpegpath); The value is the server returns the values if (value. Contains ("1")) {MessageBox.Show ("landed successfully.");            } else if (value.            Contains ("0")) {MessageBox.Show ("Login failed.");            } else {MessageBox.Show ("Unknown error."); }        }    }}
server PHP side:

<?php$name = $_post["name"];  Get user name $pwd = $_post["pwd"];    Get Password $head = $_post["Head"];    Get Avatar if (! $name | |! $pwd | |! $head) {//return value is 2, unknown error echo "2"; return;} else if ($name = = "Doozn" && $pwd = = "a12345") {$time  = date ("Ymdhis");  Get the time to name the picture $path= "c:\\login\\";      Construct the path $path.= "log". \\";   CreateFolder ($path);      Create Save Picture Directory folder $pic=base64_decode ($head);  Picture processing $filetype= ". jpg"; $newname = $path. $time. $filetype; $fq =fopen ($newname, ' w ');//Open Path Fwrite ($FQ, $pic);    Write Picture fclose ($FQ); echo "1";         The return value is 1, the login succeeds}else{echo "0";   The return value is 0, Login failed}//Create folder function CreateFolder ($path) {if (!file_exists ($path)) {CreateFolder (dirname ($path)); MkDir ($ Path, 0777);}? >
Original address: http://blog.csdn.net/qingdujun/article/details/41764521


C # Post text picture to server

Related Article

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.