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

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_36810544/article/details/88762234

需要一个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-Type
            httpRequest.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);

猜你喜欢

转载自blog.csdn.net/qq_36810544/article/details/88762234