Api---富文本

API接口:

  /// <summary>
        /// 新建项目
        /// </summary>
        /// <param name="projectVo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Result> PostProject([FromForm] ProjectVo projectVo)
        {
            Result result = new Result() { Code = 0, Message = "successs!" };
            try
            {
                using (var lifetimeScope = Container.BeginLifetimeScope())
                {
                    if (projectVo.StarTime > projectVo.EndTime)
                    {
                        result.Code = 1;
                        result.Message = "招标开始时间不能晚于结束时间!";
                        return result;
                    }

                    if (projectVo.EndTime > projectVo.OpenTime)
                    {
                        result.Code = 1;
                        result.Message = "开标时间需大于报名结束时间!";
                        return result;
                    }
                    ProjectMethods projectMethods = new ProjectMethods();
                    if(projectMethods.BlockedFileType(projectVo.FilesInput))
                    {
                        result.Code = 1;
                        result.Message = "附件类型有误!";
                        return result;
                    }
                    
                    IGjProjectService service = lifetimeScope.Resolve<IGjProjectService>();
                    service.AddOrUpdateProject(projectVo);
                }
            }
            catch (Exception ex)
            {
                result.Code = 1;
                result.Message = ex.Message;
                return result;
            }
            return result;
        }
View Code
 #region 上传富文本图片,返回url 
        /// <summary>
        /// 上传富文本图片,返回url
        /// </summary>
        /// <param name="imgVo"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult<Result> PostRichTextImg([FromForm]RichTextImgVo imgVo)
        {
            Result result = new Result() { Code = 0, Message = "" };
            if (imgVo.FilesInput != null&& (imgVo.FilesInput.FileName.Length/1024.0)>1024)
            {
                string extension = Path.GetExtension(imgVo.FilesInput.FileName);
                if (extension != ".bmp" && extension != ".jpg" && extension != ".jpeg" && extension != ".png")
                {
                    result.Code = 1;
                    result.Message = "图片上传的文件不是常用图片格式!";
                    return result;
                }
            }               
            ProjectMethods projectMethods = new ProjectMethods();
            string url = projectMethods.SaveSingleFile(imgVo.FilesInput, "Temp");
            result.Message = url;
            return result;
        }
View Code

传入的参数:

public class ProjectVo : GjProject
    {

        public string ProjectDepartmentId { get; set; }
        public string ProjectDepartments { get; set; }//乡镇流
        public string GjProjectFiles { get; set; }//附件流
        public IFormFile[] FilesInput { set; get; }//附件
    }
View Code
 public partial class GjProject
    {
        public string Guid { get; set; }
        [Required(ErrorMessage = "项目名称不能为空")]
        public string ProjName { get; set; }
        [Required(ErrorMessage = "工匠星级不能为空")]
        public int? WorkerStar { get; set; }
        [Required(ErrorMessage = "总金额不能为空")]
        public float? TotalMoney { get; set; }
        [Required(ErrorMessage = "开始报名时间不能为空")]
        public DateTime? StarTime { get; set; }
        [Required(ErrorMessage = "结束报名时间不能为空")]
        public DateTime? EndTime { get; set; }
        [Required(ErrorMessage = "浮率区间不能为空")]
        public float? AdjustRangeMin { get; set; }
        [Required(ErrorMessage = "浮率区间不能为空")]
        public float? AdjustRangeMax { get; set; }
        [Required(ErrorMessage = "所属乡镇不能为空")]
        public int? DutyDept { get; set; }
        [Required(ErrorMessage = "开标时间不能为空")]
        public DateTime? OpenTime { get; set; }
        [Required(ErrorMessage = "标书内容不能为空")]
        public string Content { get; set; }
        public int? JoinCount { get; set; }
        public string Bidder { get; set; }        
        public string LiveUrl { get; set; }
        public string LiveUrlTv { get; set; }
        public string VedioUrl { get; set; }
        public string VedioUrlTv { get; set; }
        public DateTime? AuditTime { get; set; }
        public int? Auditor { get; set; }
        public int? CreatedDetp { get; set; }
        public int? CreatedBy { get; set; }
        public DateTime? CreatedOn { get; set; }
        public int? IsDeleted { get; set; }
        public int? ModifyBy { get; set; }
        public DateTime? ModifyOn { get; set; }
        public int? Status { get; set; }
        public int? IsBack { get; set; }
        public int? Points { get; set; }
        [Required(ErrorMessage = "主管单位不能为空")]
        public int? Management { get; set; }
        [Required(ErrorMessage = "工期不能为空")]
        public int? Period { get; set; }
        public  DateTime? StartDate { get; set; }
    }
View Code
 public class RichTextImgVo
    {
       public IFormFile FilesInput { set; get; }
    }
View Code

数据访问层:

  public bool AddOrUpdateProject(ProjectVo projectVo)
        {
            using (var tran = DbContext.Database.BeginTransaction())//启动事务,中间错误再执行回滚
            {
                try
                {
                    ProjectMethods projectMethods = new ProjectMethods();
                    GjProject project = GetSingle(o => o.Guid == projectVo.Guid);
                    int? userId = userSession.GetCurrentUserId()==null?null: (int)userSession.GetCurrentUserId();
                    if (project == null)
                    {
                        project = new GjProject();
                        //创建project
                        project.Guid = Guid.NewGuid().ToString();
                        projectMethods.Setfields(project, projectVo);
                        project.JoinCount = 0;
                        UserService userService = new UserService();
                        project.CreatedDetp = userService.GetSingle(u => u.Id == userId) == null ? null : userService.GetSingle(u => u.Id == userId).DepartmentId;
                        project.CreatedBy = userId;
                        project.CreatedOn = DateTime.Now;
                        project.IsDeleted = 0;
                        project.ModifyBy = userId;
                        project.Status = 0;
                        project.IsBack = -1;
                        Add(project);
                    }
                    else
                    {
                        //修改
                        projectMethods.Setfields(project, projectVo);
                        project.ModifyBy = userId;
                        Update(project);
                        projectMethods.DeleteGjProjectFile(project.Guid, "contentfile", "", projectVo.GjProjectFiles);
                    }
                    //保存标书内容附件
                    projectMethods.SaveFile(project.Guid, "contentfile", "", projectVo.FilesInput);
                    //可报名乡镇
                    if (!string.IsNullOrEmpty(projectVo.ProjectDepartments))
                    {
                        List<GjProjectDepartment> departments = JsonSerializer.Deserialize<List<GjProjectDepartment>>(projectVo.ProjectDepartments);//projectVo.ProjectDepartments流形式,转化为List<GjProjectDepartment>类型
                        GjProjectDepartmentService departmentService = new GjProjectDepartmentService();
                        //删除旧数据
                        departmentService.GetList(d => d.ProjId == project.Guid).ToList().ForEach(d =>
                        {
                            departmentService.Remove(d);
                        });
                        foreach (GjProjectDepartment town in departments)
                        {
                            GjProjectDepartment newdata = new GjProjectDepartment();
                            newdata.Guid = Guid.NewGuid().ToString();
                            newdata.ProjId = project.Guid;
                            newdata.SysdepartmentId = town.SysdepartmentId;
                            newdata.SysdepartmentName = town.SysdepartmentName;
                            departmentService.Add(newdata);
                        }
                    }
                    tran.Commit();//对提交事务中对数据库所做的所有更改;
                }
                catch (Exception)
                {
                    tran.Rollback();//放弃当前事务中对数据库所做的所有更改。
                    throw;
                }
            }
            return true;
        }
View Code

方法类:

#region 项目表创建
        public GjProject Setfields(GjProject project, ProjectVo projectVo)
        {
            project.ProjName = projectVo.ProjName;
            project.WorkerStar = projectVo.WorkerStar;
            project.TotalMoney = projectVo.TotalMoney;
            project.StarTime = projectVo.StarTime;
            project.EndTime = projectVo.EndTime;
            project.AdjustRangeMin = projectVo.AdjustRangeMin;
            project.AdjustRangeMax = projectVo.AdjustRangeMax;
            project.DutyDept = projectVo.DutyDept;
            project.OpenTime = projectVo.OpenTime;
            project.Content = GetHtmlImageUrlList(projectVo.Content);
            project.Management = projectVo.Management;
            project.Period = projectVo.Period;
            project.StartDate = projectVo.StartDate;
            project.ModifyOn = DateTime.Now;
            return project;
        }
        #endregion

        #region 修改时把文件表中对应这个项目之前的附件信息没有的删除掉,有的话保留下来
        public void DeleteGjProjectFile(string projectId, string projCol, string projColId, string projectJoinFiles)
        {
            try
            {
                GjProjectFileService fileService = new GjProjectFileService();
                List<GjProjectFile> oldFilesList = fileService.GetList(o => o.ProjId == projectId && (string.IsNullOrEmpty(projCol) || o.ProjCol == projCol) &&
                  (string.IsNullOrEmpty(projColId) || o.ProjColId == projColId)).ToList();
                List<GjProjectFile> filesList = new List<GjProjectFile>();
                List<GjProjectFile> removeFilesList = new List<GjProjectFile>();
                if (string.IsNullOrEmpty(projectJoinFiles))//projectJoinFiles前台传的是保留的文件
                {
                    removeFilesList = oldFilesList;//如果projectJoinFiles是空的话,把项目id的删掉
                }
                else
                {
                    filesList = JsonSerializer.Deserialize<List<GjProjectFile>>(projectJoinFiles);//保留的
                    removeFilesList = oldFilesList.Where(o => !filesList.Where(i => i.Guid == o.Guid).Any()).ToList();//查询数据库中不保留的数据
                }
                foreach (GjProjectFile one in removeFilesList)
                {
                    fileService.Remove(one);//删掉数据库中不保留的数据
                }
            }
            catch (Exception ex)
            {
                throw;
            }
        }
        #endregion

        #region 保存文件,文件表
        public void SaveFile(string projectId, string projCol, string projColId, IFormFile[] formFiles)//标书
        {
            try
            {
                if (formFiles != null)
                {
                    GjProjectFileService service = new GjProjectFileService();
                    string filedocument = DateTime.Now.ToString("yyyyMMdd");

                    for (int i = 0; i < formFiles.Length; i++)
                    {

                        string fileUrl = SaveSingleFile(formFiles[i], filedocument);

                        GjProjectFile fileUpload = new GjProjectFile();
                        fileUpload.Guid = Guid.NewGuid().ToString();
                        fileUpload.ProjId = projectId;
                        fileUpload.ProjCol = projCol;
                        #region projCol"项目栏目             
                        //contentfile--标书内容附件
                        // joinerfile--报名人附件
                        // contractfile--合同附件
                        // checkfile--验收附件
                        // appraisefile--评价附件
                        // monitorfile--监督附件"
                        #endregion
                        fileUpload.ProjColId = projColId;
                        fileUpload.FileType = fileUrl.Substring(fileUrl.LastIndexOf('.') + 1);
                        fileUpload.FileName = formFiles[i].FileName;
                        fileUpload.Url = fileUrl;
                        fileUpload.CreatedOn = DateTime.Now;
                        fileUpload.CreatedBy = "";
                        service.Add(fileUpload);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        #endregion

        #region 暂时保存富文本图片
        public string SaveSingleFile(IFormFile formFile, string filedocument)
        {
            if (formFile != null)
            {
                string rootPath = "/Upload/" + filedocument;
                if (!Directory.Exists(rootPath))
                {
                    Directory.CreateDirectory(rootPath);
                }
                //扩展名fileName
                string fileName = Guid.NewGuid().ToString() + Path.GetExtension(formFile.FileName);
                string rootUrl = Directory.GetCurrentDirectory() + "/" + rootPath + "/" + fileName;
                var url = rootPath + "/" + fileName;
                File.Create(rootUrl);
                return url;
            }
            return "";
        }
        #endregion

        #region 保存富文本内容时把图片路径替换掉,把就文件夹内容移动到新文件夹内容中
        public string GetHtmlImageUrlList(string htmlText)
        {
            Regex reg = new Regex(@"<img.*?src=""(?<src>[^""]*)""[^>]*>", RegexOptions.IgnoreCase);
            MatchCollection mc = reg.Matches(htmlText); //设定要查找的字符串
            string rooturl = Directory.GetCurrentDirectory();
            string destUrl = rooturl + "/Upload/Temp";
            if (!Directory.Exists(destUrl))
            {
                Directory.CreateDirectory(destUrl);
            }

            foreach (Match m in mc)
            {
                string temp = m.Groups["src"].Value;
                if (temp.Contains("/Upload/RichTextImage/"))
                {
                    //保存
                    string sourceUrl = temp.Substring(temp.IndexOf("Upload/RichTextImage/"));
                    string targetUrl = sourceUrl.Replace("/RichTextImage/", "/Temp/");
                    File.Move(rooturl + "/" + sourceUrl, rooturl + "/" + targetUrl, true);
                    //删除
                    File.Delete(rooturl + "/" + sourceUrl);
                }
            }

            htmlText = htmlText.Replace("/RichTextImage/", "/Temp/");
            return htmlText;
        }
        #endregion

        #region 删除图片
        //删除图片
        public bool DeleteFile(string url)
        {
            try
            {
                string rootUrl = Directory.GetCurrentDirectory();
                if (!string.IsNullOrEmpty(url))
                {
                    string imgUrl = rootUrl + "/" + url;
                    if (File.Exists(imgUrl))
                    {
                        File.Delete(imgUrl);
                    }
                }
            }
            catch (Exception ex)
            {
                return false;
            }
            return true;
        }
        #endregion

        #region 验证附件类型是不是图片类型,是指定图片类型返回true
        //验证附件类型是不是图片类型,是指定图片类型返回true
        public bool CheckFileExtension(IFormFile[] FilesInput)
        {
            foreach (IFormFile formFiles in FilesInput)
            {
                if (formFiles != null)
                {
                    string extension = Path.GetExtension(formFiles.FileName);

                    if (extension != ".bmp" && extension != ".jpg" && extension != ".jpeg" && extension != ".png")
                    {
                        return false;
                    }
                }
            }

            return true;
        }
        #endregion

        #region 含有限制类型文件,返回true
        //含有限制类型文件,返回true
        public bool BlockedFileType(IFormFile[] FilesInput)
        {
            if (FilesInput != null)
            {

                string[] blockTypes = { ".exe", ".ade", ".adp", ".asa", ".ashx", ".asmx", ".asp", ".bas", ".bat", ".cdx", ".cer", ".chm", ".class", ".cmd", ".cnt", ".com", ".config", ".cpl", ".crt", ".csh", ".der", ".dll" };
                foreach (IFormFile formFiles in FilesInput)
                {

                    string extension = Path.GetExtension(formFiles.FileName);
                    if (blockTypes.Contains(extension))
                    {
                        return true;
                    }
                }
            }
            return false;
        }

        #endregion
View Code

效果图:

 

 数据库表:

 

 

 

 

 

 

 

 

 

 

 

 

 

posted @ 2022-02-23 10:43  猴猴手记  阅读(70)  评论(1编辑  收藏  举报
浏览器标题切换
浏览器标题切换end