netcore 开发问题整理(图片地址)

图片路径 在wwwroot 下才能读取

图片控件上传图片保存方法

        var result = "";
            try
            {//接收post传来的base64 图片信息
                string base64img = image;
                if (string.IsNullOrEmpty(base64img) || !base64img.Contains(","))
                {
                    return result;
                }
                //post的数据里面,加号会被替换为空格,需要重新替换回来,如果不是post的数据,则注释掉这一行
                base64img = base64img.Replace(' ', '+');
                string[] imglist = base64img.Split(',');
                //图片格式
                var imgFormat = imglist[0];
                //图片格式默认jpg
                string finalImgFormat = ".jpg";
                if (imgFormat.Contains("png"))
                {
                    finalImgFormat = ".png";
                }
                else if (imgFormat.Contains("gif"))
                {
                    finalImgFormat = ".gif";
                }
                else if (imgFormat.Contains("bmp"))
                {
                    finalImgFormat = ".bmp";
                }
                //Base64图片码
                var encodedImage = imglist[1];
                byte[] bt = Convert.FromBase64String(encodedImage);
                //获取当前的项目文件所在的目录。当使用命令启动时为执行dotnet命令所在的目录 图片必须在wwwroot文件下
                var path = Directory.GetCurrentDirectory()+"\\wwwroot";
                //图片文件夹
                string ImageFilePath = "\\TempImages\\" + DateTime.Now.Year.ToString() + DateTime.Now.Month.ToString();

                if (!Directory.Exists(path + ImageFilePath))//如果不存在就创建文件夹
                {
                    Directory.CreateDirectory(path + ImageFilePath);
                }

                //文件名
                string fileName = DateTime.Now.ToString("yyyyMMddHHmmss");

                string ImagePath = ImageFilePath + "\\" + fileName + finalImgFormat;//定义图片名称

                System.IO.File.WriteAllBytes(path + ImagePath, bt);
                //File( bt, ImagePath); //保存图片到服务器,然后获取路径  

                //保存图片结果 返回不需要全部地址 
                return ImagePath;

            }
            catch (Exception ex)
            {

                return result;
            }
 //给回传的图片地址 赋值 用于提交后台时获取对应的字段值
<input asp-for="Imgurl" type="hidden" id="cuploadImgurl" value="" />

使用的图片插件为 Cupload 需要修改js

 

posted @ 2021-10-27 14:55  哈佛  阅读(172)  评论(0编辑  收藏  举报