C#在CS端把图片通过Json或者fromdata的格式上传到服务器接口
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
C#在CS端把图⽚通过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("该路径为空");
}
}
新加:通过HTTP协议传⼊Json参数请求接⼝
public string CommndData(string url,string json)
{
//url = "https:///sdfdfdfev/ssyz/1/getSleepState";
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
req.Method = "POST";
req.Timeout = 800;
req.ContentType = "application/json";
//byte[] data = Encoding.UTF8.GetBytes("{\"sn\":\"AC320D3FA8C7\"}");
byte[] data = Encoding.UTF8.GetBytes(json);
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) {
result = reader.ReadToEnd();
}
return result;
}
.。