• 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:UsersLenovoPictures联想锁屏壁纸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("该路径为空");
                }
            }

    .

  • 相关阅读:
    【读书笔记】MSDN 上关于加密解密的一个例子
    【读书笔记】创建泛型编程类 由链表而深入
    HDFS数据加密空间Encryption zone
    各种数据库的连接方法
    Java基础5
    Java基础4
    Java基础2
    博客优化、收录、RSS技巧
    Java基础3
    Java基础8
  • 原文地址:https://www.cnblogs.com/xunmengrenli/p/15206675.html
Copyright © 2020-2023  润新知