C#webapi接收app发送的post请求,包括数据和图片

【1】HttpContext获取http请求

HttpContext context = HttpContext.Current;

在业务层需要取得当前页面层的Session,Request,Response,Server时可以通过 Http.Current来获得

参考https://www.cnblogs.com/zhouyunbaosujina/p/3164956.html

【2】 判断当前页面是否接收到了Post请求 

context.Request.HttpMethod.ToLower().Equals("post")

【3】当前页面获取到的参数和参数值

参考https://q.cnblogs.com/q/108321/

context.Request.Form.AllKeys

foreach (var key in context.Request.Form.AllKeys)
            {
                var val=context.Request.Form[key];
            }

比如参数名Unit,对应参数值就是

context.Request.Form["Unit"]

【4】获取上传的图片,以文件流的形式传过来

context.Request.Form["base64Code1"]

上传多个文件的情况下,用逗号" , "分割文件(备注,多个文件时上传多个文件流参数时遇到问题,获取不到完整的post请求,即只能获取部分参数,故改成只上传一个文件流参数,然后分割开)

var base64Code = context.Request.Form["base64Code1"].Split(',');

【5】文件路径

Server.MapPath方法作用

MapPath方法用来返回与Web服务器上的指定虚拟路径相对应的物理文件路径。

语法
Server.MapPath(path);

参数
path表示Web服务器上的虚拟路径,如果path值为空,则该方法返回包含当前应用程序的完整物理路径。

注意事项

Server.MapPath()有时在程序调试时会提示“当前上下文中不存在名称“Server””错误,从而不支持函数Server.MapPath()的使用。尽管引用了命名空间“using System.Web;”也是无济于事,此时就需要使用其全名,或者是当前使用Server.MapPath()函数的类继承自System.Web.UI.Page。

参考https://blog.csdn.net/nnn_net/article/details/71080905

(1)配置文件里的路径信息

string PicPath = System.Configuration.ConfigurationManager.AppSettings["PicPath"];

(2)生成新的文件名

string fileExt = "jpg"; //文件扩展名,不含“.” 
string newFileName = GetTimeStamp() + "_"+(i+1)+"." + fileExt; //随机生成新的文件名

GetTimeStamp是获取时间戳的方法

(3)文件路径,如果不存在,就去创建

string path = "\\";

string pathY = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\");
                    if (!Directory.Exists(pathY))
                    {
                        Directory.CreateDirectory(pathY);
                    }

(4)保存图片路径--绝对路径
string newFilePath = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\" + newFileName);

【6】上传图片

string str = base64Code[i];

if (str != null)加上 && str!=""空的判断

Image img = Base64ToImg(str);//添加引用Image--using System.Drawing;
img.Save(newFilePath, System.Drawing.Imaging.ImageFormat.Png);
string ypath = PicPath + "UploadImg/avatars/yt/" + newFileName;

解析base64编码获取图片的方法Base64ToImg

MemoryStream----http://www.cnblogs.com/JimmyZheng/archive/2012/04/14/2446507.html#u02

【7】//保存缩略图
                /*if (img1.Height > 0 && img1.Width > 0)
                {
                    Image thumbimg = img1.GetThumbnailImage(Convert.ToInt32(img1.Width * 0.4), Convert.ToInt32(img1.Height * 0.4), null, IntPtr.Zero);
                    thumbimg.Save(newThumbnailPath);

                }*/

【8】附代码如下

[HttpPost, Route("Uploadinf")]

public PostResult Uploadinf()
        {
            HttpContext context = HttpContext.Current;
            string param = string.Empty;
            if (context.Request.HttpMethod.ToLower().Equals("post"))
            {
                param += "[POST]";
            }
            foreach (var key in context.Request.Form.AllKeys)
            {
                param += key + ":" + context.Request.Form[key];
            }
            //for(int i=0; i             //{
            //    param += context.Request.Form[i] + ":" + context.Request.Form[i];
            //}

            PostResult result = new PostResult();

            T_DATA_PE tp = new T_DATA_PE();

            tp.Unit = int.Parse(context.Request.Form["Unit"]);
            tp.style = int.Parse(context.Request.Form["style"]);
            tp.community = int.Parse(context.Request.Form["community"]);
            tp.address = context.Request.Form["address"];
            tp.monitortime = Convert.ToDateTime(context.Request.Form["monitortime"]);
            tp.description = context.Request.Form["description"];
            tp.status = 0;
            


            try
            {
                System.Web.Mvc.Controller controller = new HomeController();

                #region 上传图片
                string path = "\\";// context.Request.Form["path"]
                //string base64Code1 = context.Request.Form["base64Code1"];
                //string base64Code2 = context.Request.Form["base64Code2"];
                //string base64Code3 = context.Request.Form["base64Code3"];
                //用“,”分割文件流
                var base64Code = context.Request.Form["base64Code1"].Split(',');
                for (var i = 0; i < base64Code.Length; i++) 
                {
                    string str = base64Code[i];
                    string PicPath = System.Configuration.ConfigurationManager.AppSettings["PicPath"];
                    string fileExt = "jpg"; //文件扩展名,不含“.” 
                    string newFileName = GetTimeStamp() + "_"+(i+1)+"." + fileExt; //随机生成新的文件名
                    string pathY = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\");
                    if (!Directory.Exists(pathY))
                    {
                        Directory.CreateDirectory(pathY);
                    }
                    //保存图片路径--绝对路径
                    string newFilePath = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\" + newFileName);
                    //判断一下是否上传了图片
                    if (str != null)
                    {
                        Image img = Base64ToImg(str);//Image--using System.Drawing;
                        img.Save(newFilePath, System.Drawing.Imaging.ImageFormat.Png);
                        string ypath = PicPath + "UploadImg/avatars/yt/" + newFileName;
                        if (i == 0) 
                        {
                            tp.image1 = ypath;
                        }
                        else if (i == 1) 
                        {
                            tp.image2 = ypath;
                        }
                        else if (i == 2)
                        {
                            tp.image3 = ypath;
                        }
                        
                    }
                }
                
                /*string PicPath = System.Configuration.ConfigurationManager.AppSettings["PicPath"];
                string fileExt = "jpg"; //文件扩展名,不含“.” 
                string newFileName1 = GetTimeStamp() + "_1." + fileExt; //随机生成新的文件名*/
                //string newFileName2 = GetTimeStamp() + "_2." + fileExt; //随机生成新的文件名
                //string newFileName3 = GetTimeStamp() + "_3." + fileExt; //随机生成新的文件名
                //string newThumbnailFileName = "thumb_" + newFileName; //随机生成缩略图文件名

                /*string upLoadPath1 = "\\UploadImg\\avatars\\yt\\" + newFileName1;//上传原图目录相对路径*/
                //string upLoadPath2 = "\\UploadImg\\avatars\\yt\\" + newFileName2;
                //string upLoadPath3 = "\\UploadImg\\avatars\\yt\\" + newFileName3;
                //string upLoadPathS = "\\UploadImg\\avatars\\slt\\" + newThumbnailFileName;//上传缩略图目录相对路径

                //是否存在存放缩略图和原图的文件夹 没有则创建
                //string pathS = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\slt\\");
                /*string pathY = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\");*/

                /*if (!Directory.Exists(pathS))
                {
                    Directory.CreateDirectory(pathS);
                }*/
                /*if (!Directory.Exists(pathY))
                {
                    Directory.CreateDirectory(pathY);
                }*/
                //string newFilePath = path + "UploadImg\\avatars\\yt\\" + newFileName; //上传后原图的路径
                //string newThumbnailPath = path + "UploadImg\\avatars\\slt\\" + newThumbnailFileName; //上传后的缩略图路径 
                //保存图片路径--绝对路径
                /*string newFilePath1 = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\" + newFileName1);*/
                //string newFilePath2 = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\" + newFileName2);
                //string newFilePath3 = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\yt\\" + newFileName3);
                //string newThumbnailPath = System.Web.HttpContext.Current.Server.MapPath(path + "UploadImg\\avatars\\slt\\" + newThumbnailFileName);
                #region 检查上传的物理路径是否存在,不存在则创建
                //if (!Directory.Exists(path))
                //{
                //    Directory.CreateDirectory(path);
                //}
                #endregion

                #region 保存文件  图片剪裁
                //判断一下是否上传了图片
                /*if (base64Code1 != null)
                {
                    Image img1 = Base64ToImg(base64Code1);//Image--using System.Drawing;
                    img1.Save(newFilePath1, System.Drawing.Imaging.ImageFormat.Png);
                    string ypath1 = PicPath + "UploadImg/avatars/yt/" + newFileName1;
                    tp.image1 = ypath1;                   
                }*/
                /*if (base64Code2 != null)
                {
                    Image img2 = Base64ToImg(base64Code2);//Image--using System.Drawing;
                    img2.Save(newFilePath2, System.Drawing.Imaging.ImageFormat.Png);
                    string ypath2 = PicPath + "UploadImg/avatars/yt/" + newFileName2;
                    tp.image2 = ypath2;
                    
                }
                if (base64Code1 != null)
                {
                    Image img3 = Base64ToImg(base64Code3);//Image--using System.Drawing;
                    img3.Save(newFilePath3, System.Drawing.Imaging.ImageFormat.Png);
                    string ypath3 = PicPath + "UploadImg/avatars/yt/" + newFileName3;
                    tp.image3 = ypath3;
                }*/
                
                
                
                //保存缩略图
                /*if (img1.Height > 0 && img1.Width > 0)
                {
                    Image thumbimg = img1.GetThumbnailImage(Convert.ToInt32(img1.Width * 0.4), Convert.ToInt32(img1.Height * 0.4), null, IntPtr.Zero);
                    thumbimg.Save(newThumbnailPath);

                }*/
                               
                #endregion                
                
                
                //string spath = PicPath + "UploadImg/avatars/slt/" + newThumbnailFileName;


                
                #endregion

                List list = new List();
                list.Add(tp);
                int addresult = ef.Insert(list);
                if (addresult > 0)
                {
                    T_DATA_PE temp = ef.FindAll(p => p.Unit == tp.Unit && p.style == tp.style && p.community == tp.community).OrderByDescending(p => p.monitortime).FirstOrDefault();
                    result.flag = true;
                    result.msg = "发布成功";
                    result.postid = temp.image1.ToString()+" ; "+temp.image2.ToString() + " ; "+temp.image3.ToString() + " ; ";
                }
                else
                {
                    result.flag = false;
                    result.msg = "发布失败";
                    result.postid = "";
                }
            }
            catch (Exception e)
            {

                result.flag = false;
                result.msg = "接口异常:" + e.ToString();
                result.postid = "";
            }
            return result;
        }

//获取当前时间段额时间戳
        public string GetTimeStamp()
        {
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalMilliseconds).ToString();
        }

        ///


        /// 解析base64编码获取图片
        ///

        ///
        ///
        private Bitmap Base64ToImg(string base64Code)
        {
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(base64Code));
            return new Bitmap(stream);
        }

你可能感兴趣的:(C#,webapi)