restful API接口接收图片 C#实现

编程入门 行业动态 更新时间:2024-10-08 19:46:52

restful API<a href=https://www.elefans.com/category/jswz/34/1771365.html style=接口接收图片 C#实现"/>

restful API接口接收图片 C#实现

需要一个web API接口用来接收图片,将客户上传的图片保存到服务器,如果直接用参数接收图片的base64编码的话,会得到参数超过最大长度的错误,那就换方式咯,改用frombody传递。
服务端代码:

[HttpPost]        
public string ImageUpload([FromBody]ImageUploadBody image_body)
{JsonViewData viewData = new JsonViewData() { isSuccessful = true, message = "" };try{string file_name = DateTime.Now.ToString("yyyyMMddHHmmss") + ".jpg";string save_path = System.Web.Configuration.WebConfigurationManager.AppSettings["UploadSavePath"];CBase64Helper.Base64StringToImage(image_body.image, System.IO.Path.Combine(save_path, file_name));}catch (Exception ex){viewData.isSuccessful = false;viewData.message = ex.Message;}return JsonHelper.SerializeObject(viewData);
}

CBase64Helper.cs

    public class ImageUploadBody{public string name;public string image;}public static class CBase64Helper{public  static string ImgToBase64String(string Imagefilename){try{Bitmap bmp = new Bitmap(Imagefilename);MemoryStream ms = new MemoryStream();bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);byte[] arr = new byte[ms.Length];ms.Position = 0;ms.Read(arr, 0, (int)ms.Length);ms.Close();return Convert.ToBase64String(arr);}catch (Exception ex){return null;}}public static void Base64StringToImage(string strbase64, string save_path){try{byte[] arr = Convert.FromBase64String(strbase64);MemoryStream ms = new MemoryStream(arr);System.Drawing.Image img = System.Drawing.Image.FromStream(ms);img.Save(save_path, System.Drawing.Imaging.ImageFormat.Jpeg);}catch (Exception ex){}}}

客户端代码,这里是用控制台程序上传的,页面JS代码因为不需要就没弄

    public class PostImageData{public string name;public string image;}public class JsonViewData{public bool isSuccessful{get;set;}public string message{get;set;}}public static class ImageUploadTool{public static bool UploadToServer(string img_file, ILog logger){string url = "http://xxxxx/api/ImageUpload";string method = "POST";string base64 = CBase64Helper.ImgToBase64String(img_file);            PostImageData post_data = new PostImageData();post_data.image = base64;post_data.name = "";string bodys = Newtonsoft.Json.JsonConvert.SerializeObject(post_data);HttpWebRequest httpRequest = null;HttpWebResponse httpResponse = null;httpRequest = (HttpWebRequest)WebRequest.Create(url);httpRequest.Method = method;//根据API的要求,定义相对应的Content-TypehttpRequest.ContentType = "application/json; charset=UTF-8";if (0 < bodys.Length){byte[] data = Encoding.UTF8.GetBytes(bodys);using (Stream stream = httpRequest.GetRequestStream()){stream.Write(data, 0, data.Length);}}try{httpResponse = (HttpWebResponse)httpRequest.GetResponse();}catch (WebException ex){httpResponse = (HttpWebResponse)ex.Response;}if (httpResponse.StatusCode != HttpStatusCode.OK){logger.Error(img_file + " Upload failed, http error code: " + httpResponse.StatusCode);                Stream st = httpResponse.GetResponseStream();StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));logger.Error(reader.ReadToEnd());return false;}else{Stream st = httpResponse.GetResponseStream();StreamReader reader = new StreamReader(st, Encoding.GetEncoding("utf-8"));string str_res = reader.ReadToEnd();JsonViewData res = Newtonsoft.Json.JsonConvert.DeserializeObject<JsonViewData>(str_res);logger.Info(img_file + " Uploaded, success: " + res.isSuccessful.ToString());return res.isSuccessful;}            }}

客户端调用的时候直接:

CImageUploadTool.UploadToServer(img_path);

更多推荐

restful API接口接收图片 C#实现

本文发布于:2024-02-27 19:57:02,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1766110.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:接口   图片   restful   API

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!