1. 程式人生 > 其它 >C#在C/S端把圖片通過Json或者fromdata的格式上傳到伺服器介面

C#在C/S端把圖片通過Json或者fromdata的格式上傳到伺服器介面

首先是Fromdata格式的上傳伺服器

注:可以使用PostMan工具進行介面測試 詳情自百度。

以下是Fromdata格式上傳伺服器程式碼

           //根據按鈕開啟一個圖片 第一步
           if (open.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = open.FileName;
                pictureBox1.ImageLocation = this.textBox1.Text;
                pictureBox1.SizeMode 
= PictureBoxSizeMode.Zoom; }     /// <summary> /// 使用 POST 方式提交中文資料 使用Uri地址、Token、傳送方式預設Form、對應的介面資料...... 第二步 /// </summary> public void SendPostData(string Url) { // POST 方式通過在頁面內容中填寫引數的方法來完成資料的提交。由於提交的引數中可以說明使用的編碼方式,所以理論上能獲得更大的相容性。 byte
[] fileContent1 = File.ReadAllBytes(pictureBox1.ImageLocation); Encoding myEncoding = Encoding.GetEncoding("gb2312"); //確定用哪種編碼方式 //對應的介面資料以及值有多少寫多少 string param = HttpUtility.UrlEncode("strFile", myEncoding) + "=" + HttpUtility.UrlEncode(pictureBox1.ImageLocation, myEncoding) + "
&" + HttpUtility.UrlEncode("appId", myEncoding) + "=" + HttpUtility.UrlEncode("1400495610", myEncoding) + "&" + HttpUtility.UrlEncode("programeId", myEncoding) + "=" + HttpUtility.UrlEncode("165", myEncoding) + "&" + HttpUtility.UrlEncode("suffix", myEncoding) + "=" + HttpUtility.UrlEncode(".jpg", myEncoding) + "&" + HttpUtility.UrlEncode("roomId", myEncoding) + "=" + HttpUtility.UrlEncode("713", myEncoding); //string jsonStr = @"{""roomId"":3, ""programeId"":""135"", ""appId"":""123"", ""suffix"":""jpg"", ""strFile"":""C:\Users\Lenovo\Pictures\聯想鎖屏桌布\8482111.jpg""}"; byte[] paramBytes = Encoding.ASCII.GetBytes(param); //引數轉化為 ASCII 碼 HttpWebRequest httpWebRequest = WebRequest.Create(Url) as HttpWebRequest; httpWebRequest.Method = "POST"; httpWebRequest.ContentType = "application/json;charset=gb2312"; httpWebRequest.ContentLength = paramBytes.Length; httpWebRequest.Headers.Add("token", "token值....."); using (Stream reqStream = httpWebRequest.GetRequestStream()) { reqStream.Write(paramBytes, 0, paramBytes.Length); } HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; // 獲取響應 if (httpWebResponse != null) { using (StreamReader sr = new StreamReader(httpWebResponse.GetResponseStream())) { string content = sr.ReadToEnd(); } httpWebResponse.Close(); } }

以下是Json格式上傳

//開啟選擇一個Image圖片
 private void button3_Click(object sender, EventArgs e)
        {
            if (open.ShowDialog() == DialogResult.OK)
            {
                this.textBox1.Text = open.FileName;
                byte[] name = SaveImage(open.FileName);
                ImgPath = Convert.ToBase64String(name);
                pictureBox1.ImageLocation = this.textBox1.Text;
                pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;
            }
        }

//上傳到伺服器的上 根據一個地址和一個實體類對應著介面的所需的資料
  public void SendData(string url,Model.Body model)
        {
            //Model.Data modelresult = new Model.Data();
           
            var param = Newtonsoft.Json.JsonConvert.SerializeObject(model);
            WebClient wc = new WebClient();
            wc.Headers.Add("Content-Type", "application/json");
            wc.Headers.Add("token", "07A4262F562EC8915F862F91AF268FE6");
            var bs = wc.UploadData(url, System.Text.Encoding.UTF8.GetBytes(param));
            
            var rtn = System.Text.Encoding.UTF8.GetString(bs);
            var result = Newtonsoft.Json.JsonConvert.DeserializeObject<Model.Data>(rtn);
            MessageBox.Show(result.data);
            DownPath = result.data;
        }
//呼叫時就這樣
 private void button1_Click(object sender, EventArgs e)
        {
            var model = new Model.Body() { roomId = "713", programeId = "165", appId = "1400495610", suffix = ".jpg", strFile = ImgPath };
            SendData("介面地址",model);
        }
//實體類
 public class Body
    {
        public string roomId { get; set; }
        public string programeId { get; set; }
        public string appId { get; set; }
        public string suffix { get; set; }
        public string strFile { get; set; }
    }
   
    class Data
    {
        public string data { get; set; }
        public int status { get; set; }
        public string msg { get; set; }
    }

根據data裡面返回的地址下載

 public void DownLoad(string DownPath)
        {
            if (DownPath != null)
            {
                WebRequest imgRequest = WebRequest.Create(DownPath);

                HttpWebResponse res;
                try
                {
                    res = (HttpWebResponse)imgRequest.GetResponse();
                }
                catch (WebException ex)
                {

                    res = (HttpWebResponse)ex.Response;
                }

                if (res.StatusCode.ToString() == "OK")
                {
                    System.Drawing.Image downImage = System.Drawing.Image.FromStream(imgRequest.GetResponse().GetResponseStream());

                    string deerory = string.Format(@"D:\img\{0}\", DateTime.Now.ToString("yyyy-MM-dd"));

                    string fileName = string.Format("{0}.jpg", DateTime.Now.ToString("HHmmssffff"));


                    if (!System.IO.Directory.Exists(deerory))
                    {
                        System.IO.Directory.CreateDirectory(deerory);
                    }
                    downImage.Save(deerory + fileName);
                    downImage.Dispose();
                }
            }
            else
            {
                MessageBox.Show("該路徑為空");
            }
        }

.