JSON資料交換(文字、圖片),使用Newtonsoft.Json.dll
操作畫面
備註:
圖片會先轉換成Base64
PHP JSON資料交換,請參考
程式碼
//顯示資料/JSON
private void button1_Click(object sender, EventArgs e)
{
dataGridView1.DataSource = null;
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create("http://localhost/xuan/wsLine.php");
request.Method = "GET";
request.Timeout = 5000;
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream reciveStream = response.GetResponseStream();
StreamReader readStream = new StreamReader(reciveStream, Encoding.UTF8);
String jsonString = readStream.ReadToEnd().Trim();
List<iMessage> messages = (List<iMessage>)JsonConvert.DeserializeObject(jsonString, typeof(List<iMessage>));
dataGridView1.DataSource = messages;
response.Close();
}
//寫入資料/JSON
private void btnSubmit_Click(object sender, EventArgs e)
{
String urlString = String.Format("http://locahost/xuan/wsLine.php?action=insert&dirId={0}",txtName.Text);
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlString);
request.Method = "POST";
String json = JsonConvert.SerializeObject(this.messages);
using (var streamWriter = new StreamWriter(request.GetRequestStream()))
{
streamWriter.Write(json);
}
var httpResponse = (HttpWebResponse)request.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
var responseText = streamReader.ReadToEnd();
Console.Write(responseText);
//Now you have your response.
//or false depending on information in the response
}
httpResponse.Close();
this.Close();
}
//圖片<->Base64
class Utilis
{
public static string ImageToBase64(String imageFilePath, System.Drawing.Imaging.ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
Image image = Image.FromFile(imageFilePath);
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
public static Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
}