最近由於項目需要實現c#提交文字及數據至服務器,因此研究了一下c# php數據傳送;
下面用一個示例來演示,c# post文字+圖片 ,php端接收;
post提交數據核心代碼(post數據提交)
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 { ////// 向服務器post文字和圖片 /// ///url ///用戶名 ///密碼 ///頭像地址 ///返回服務器返回值 public string post(string url,string userName, string userPwd, string jpegPath) { //將圖片轉化為byte[]再轉化為string string array = Convert.ToBase64String(imageToByteArray(jpegPath)); //構造post提交字段 string para = name=+userName+&pwd=+userPwd+&head=+HttpUtility.UrlEncode(array); #region HttpWebRequest寫法 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()) { //提交數據 reqStream.Write(bytePara, 0, para.Length); } //獲取服務器返回值 HttpWebResponse httpWebResponse = (HttpWebResponse)httpWeb.GetResponse(); Stream stream = httpWebResponse.GetResponseStream(); StreamReader streamReader = new StreamReader(stream, Encoding.GetEncoding(utf-8)); //獲得返回值 string result = streamReader.ReadToEnd(); stream.Close(); #endregion //將服務器返回值返回 return result; } ////// 圖片轉為Byte字節數組 /// ///路徑 ///字節數組 private byte[] imageToByteArray(string FilePath) { using (MemoryStream ms = new MemoryStream()) { using (Image imageIn = Image.FromFile(FilePath)) { using (Bitmap bmp = new Bitmap(imageIn)) { bmp.Save(ms, imageIn.RawFormat); } } return ms.ToArray(); } } } }
一、c#客戶端
為了方便說明,我直接簡化了,一個提交按鈕就好了。
二、需要提交的圖片
該圖片存放在俺的E盤根目錄下面~~~~~(貼吧隨便抓的一張圖片)
path = @E:head.jpg;
三、php服務端
接收圖片後存放至,path = @C:Loginlog;
附錄:
c#端代碼:
c#界面簡單代碼~~~~~(該代碼可略過~~~~~)
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(); } ////// 提交按鈕,提交post數據 /// /// /// private void btnpost_Click(object sender, EventArgs e) { //postClass為數據提交類 postClass ps = new postClass(); string url = @http://localhost/login.php; string name = DooZn; string pwd = a12345; string jpegPath = @E:head.jpg; //提交數據 string value = ps.post(url,name,pwd,jpegPath); //value為服務器返回值 if (value.Contains(1)) { MessageBox.Show(登陸成功.); } else if (value.Contains(0)) { MessageBox.Show(登陸失敗.); } else { MessageBox.Show(未知錯誤.); } } } }