重邮项目(发布公告)(下)

由于代码量实在是太多,所以只能分为三个部分进行发布,请各位谅解。

上期讲到公告的新增,这次我们要讲公告的修改,以及数据的回填。这次数据的回填还需要回填图片,将我们前面转换成内存流的图片在重新转换回来。

第四部分,修改公告信息,修改公告信息除了需要查询数据库中的数据以外还需要查询项目中的数据。查询项目中存放图片,文本,字体,标签的文件夹是否需要更改。

#region 4.修改公告信息
        /// <summary>
        /// 4.1 修改公告的试图
        /// </summary>
        /// <param name="noticeId"></param>
        /// <returns></returns>
        public ActionResult UpdateNotice(int? noticeId)
        {
            if (Session["UserID"] != null)
            {
                //清空session
                Session.Remove("sessionFiles");
                ViewBag.noticeId = noticeId;
                return View();
            }
            else
            {
                //重定向到登录       
                return Redirect("/Main/Login");
            }
        }

        /// <summary>
        /// 4.2 根据公告ID查询公告信息
        /// </summary>
        /// <param name="NoticeID"></param>
        /// <returns></returns>
        public ActionResult SelectNoticeByNoticeID(int NoticeID)
        {
            try
            {
                #region 1.0 根据公告id查询出公告的信息
                //根据公告id查询出公告的信息
                NoticeVo notice = (from tbNotices in myModel.PW_NoticeTable
                                   join tbNoticeTypeDetail in myModel.SYS_NoticeTypeDetail on tbNotices.NoticeTypeDetailID equals tbNoticeTypeDetail.NoticeTypeDetailID
                                   join tbNoticeType in myModel.SYS_NoticeTypeTable on tbNoticeTypeDetail.NoticeTypeID equals tbNoticeType.NoticeTypeID
                                   join tbTeacher in myModel.PW_Teacher on tbNotices.UserID equals tbTeacher.UserID
                                   where tbNotices.NoticeID == NoticeID
                                   select new NoticeVo
                                   {
                                       NoticeID = tbNotices.NoticeID, //公告ID
                                       UserID = tbNotices.UserID,   //用户ID
                                       NoticeTypeDetailID = tbNotices.NoticeTypeDetailID, //公告类型明细ID
                                       NoticeTypeID = tbNoticeType.NoticeTypeID,  //公告类型ID
                                       AcademeID = tbNotices.AcademeID,  //学院ID
                                       NoticeName = tbNotices.NoticeName, //公告标题
                                       ReleaseTime = tbNotices.ReleaseTime,//发布时间
                                       schoolRelated = tbNotices.schoolRelated, //是否跟学校有关
                                       NoticeContent = tbNotices.NoticeContent, //公告内容 这里是txt文件的名称
                                       BrowsingTimes = tbNotices.BrowsingTimes, //浏览次数
                                       Overhead = tbNotices.Overhead,//是否指定
                                       New = tbNotices.New, //公告热度天数
                                       Editor = tbTeacher.TeacherName, //发布人员名称
                                       NoticeTypeName = tbNoticeType.NoticeTypeName, //公告类型名称
                                       NoticeTypeDetailName = tbNoticeTypeDetail.NoticeTypeDetailName,//公告类型明细名称
                                       ReleaseTimeStr = tbNotices.ReleaseTime.ToString()//发布时间 日期格式转换后
                                   }).Single();
                
                #endregion

                #region 1.1 查询轮播图信息
                List<PW_NoticeCarousel> pwNoticeCarousels = (from tbNoticeCarousel in myModel.PW_NoticeCarousel
                                                             where tbNoticeCarousel.NoticeID == NoticeID
                                                             select tbNoticeCarousel).ToList();
                if (pwNoticeCarousels.Count > 0)
                {
                    notice.noticeCarousel = true;//轮播为true
                    notice.NoticeCarouselImage = pwNoticeCarousels[0].NoticeCarousel;//公告轮播的图片地址
                }
                #endregion

                #region 1.2 加载公告内容
                string textFileName = Server.MapPath("~/Document/Notice/Text/") + notice.NoticeContent;
                if (System.IO.File.Exists(textFileName))
                {
                    //文件存在
                    notice.NoticeContent = System.IO.File.ReadAllText(textFileName);
                }
                else
                {
                    //文件不存在
                    notice.NoticeContent = "<p>没有找到公告内容,可能文件已经丢失;请重新编辑发布</p>";
                }
                #endregion

                #region  1.3 读取附件信息
                List<FilesVo> sessionFiles = (from tbFile in myModel.PW_File
                                              join tbNoticeTable in myModel.PW_NoticeTable on tbFile.NoticeID equals tbNoticeTable.NoticeID
                                              join tbFileType in myModel.SYS_FileType on tbFile.FileTypeID equals tbFileType.FileTypeID
                                              where tbFile.NoticeID == NoticeID
                                              select new FilesVo
                                              {
                                                  FileID = tbFile.FileID,
                                                  FileTypeID = tbFile.FileTypeID,
                                                  Files = tbFile.Files,
                                                  FileTypeName = tbFileType.FileTypeName,
                                                  FileName = tbFile.Files
                                              }).ToList();
                for (int i = 0; i < sessionFiles.Count; i++)
                {
                    //通过正则表达式获取文件名称
                    string strFileName = Regex.Match(sessionFiles[i].Files, "(?<=fileName=).+?(?=\")").Value;
                    sessionFiles[i].FileName = strFileName;
                    sessionFiles[i].FileGuid = Guid.NewGuid().ToString("N");
                }
                List<FilesVo> oldSessionFiles = new List<FilesVo>();
                foreach (FilesVo file in sessionFiles)
                {
                    oldSessionFiles.Add(file);
                }  
                //数据库提取数据 1 3 4
                Session["sessionFiles"] = sessionFiles;
                //记录原来的附件 1 2 
                Session["oldSessionFiles"] = oldSessionFiles;


                #endregion

                return Json(notice, JsonRequestBehavior.AllowGet);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return Json(null, JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 4.3 修改公告信息
        /// </summary>
        /// <param name="pwNotice"></param>
        /// <param name="noticeCarouseImage"></param>
        /// <param name="noticeCarousel"></param>
        /// <returns></returns>
        [ValidateInput(false)]//由于要存入HTML,关闭验证
        /*[ValidateInput(false)]取消危险字符的验证 如 “<> %$#”等等 。
          为了安全起见,正常的Post提交是不允许提交诸如<>$/等敏感字符的(有点类似脚本注入),
         * 如果你有必要提交这些东西的话,就需要加上ValidateInput标签,比如富文本编辑的时候*/
        public ActionResult UpdateNoticeInfor(PW_NoticeTable pwNotice, HttpPostedFileBase noticeCarouseImage, string noticeCarousel)
        {
            ReturnJson msg = new ReturnJson();
            try
            {
                //检查公告标题和内容不为空
                if (!string.IsNullOrEmpty(pwNotice.NoticeName) && !string.IsNullOrEmpty(pwNotice.NoticeContent))
                {
                    #region 1.0 根据公告ID查询出原始的公告信息
                    //查询原始公告信息
                    PW_NoticeTable dbNotice = (from tbNoticeTable in myModel.PW_NoticeTable
                                               where tbNoticeTable.NoticeID == pwNotice.NoticeID
                                               select tbNoticeTable).Single();
                    #endregion
                    #region 1.1 目录结构判断
                    //检查 存放公告内容的 目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Notice/Text/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Notice/Text/"));
                    }
                    //检查 存放轮播图片的 目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Notice/NoticeCarousel/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Notice/NoticeCarousel/"));
                    }
                    //检查 存放附件 目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Notice/Attachment/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Notice/Attachment/"));
                    }
                    //检查 存放正文内容图片的 目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Notice/Image/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Notice/Image/"));
                    }
                    #endregion
                    #region 1.2 修改公告内容:修改.txt文件 处理富文本图片文本 修改数据库内容
                    //处理发布公告的图片
                    //原始的图片 1  2  
                    //修改后图片 1 3 4  页面传递过来noticeContent
                    //1
                    //3  4
                    #region 1.2.1 处理发布公告中的图片(富文本框中的图片)
                    /*
                     * 处理图片的思路:
                    修改之前的图片文件 1 2  修改以后的图片 1 3 4
                       处理修改之前的老图片思路:
                       获取之前的txt: oldFilePath,通过正则得到oldimages:  oldSavedImageListBefore
                       获取现在的txt:FilePath,通过正则得到images:  oldSavedImageListAfter
                       对得到的图片进行比较
                       例如:oldSavedImageListBefore  1 2
                             oldSavedImageListAfter  1 
                             那么图片2 需要删除掉 从Image文件夹中删除
                       处理新添加图片的思路:
                       例如:图片 3 4通过正则匹配 然后从临时文件夹Temp 移动到Image 文件夹
                   */
                    //修改前从.txt文件中匹配出来的图片 1 2 
                    List<string> oldSavedImageListBefore = new List<string>();
                    //提交修改后从.txt文件中匹配出来的图片 1 
                    List<string> oldSavedImageListAfter = new List<string>();
                    //txt文件名称
                    string fileName;
                    //txt文件路径
                    string filePath;
                    string oldFilePath = Server.MapPath("~/Document/Notice/Text/") + dbNotice.NoticeContent;
                    if (System.IO.File.Exists(oldFilePath)) //文件存在
                    {
                        //读取原始的文本内容
                        string oldTextContent = System.IO.File.ReadAllText(oldFilePath);
                        //匹配出文件名称 保存到oldSavedImageListBefore列表中
                        MatchCollection oldBeforeMatchs = Regex.Matches(oldTextContent, "(?<=/Document/Notice/Image/).+?(?=\".+?/>)");
                        foreach (Match match in oldBeforeMatchs) {
                            oldSavedImageListBefore.Add(match.Value);
                        }
                        //获取文件名称
                        fileName = dbNotice.NoticeContent;
                        //文件路径
                        filePath = oldFilePath;
                    }
                    else {
                        //-------文件不存在
                        fileName = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "-" + Guid.NewGuid() + ".txt";
                        //文件路径
                        filePath = Server.MapPath("~/Document/Notice/Text/") + fileName;
                    }

                    //新的文件内容  修改后的公告内容
                    string textContent = pwNotice.NoticeContent;//页面传递过来的数据
                    //修改后的老图片:旧的图片可能会被删除 或则保留
                    // 1 
                    MatchCollection oldAfterMatchs = Regex.Matches(textContent, "(?<=/Document/Notice/Image/).+?(?=\".+?/>)");
                    foreach (Match match in oldAfterMatchs)
                    {
                        oldSavedImageListAfter.Add(match.Value);
                    }
                    //oldSavedImageListBefore与  oldSavedImageListAfter对比两个图片列表
                    // 1 2 
                    foreach (string str in oldSavedImageListBefore)//循环之前的一个列表
                    {
                      
                        if (!oldSavedImageListAfter.Contains(str)) {
                            //如果该图片不包含在修改以后的图片列表中 则需要删除该图片
                            //获取删除图片的路径
                            string strRemoveImagePath = Server.MapPath("~/Document/Notice/Image/") + str;
                            //删除文件
                            try
                            {
                                System.IO.File.Delete(strRemoveImagePath);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e);
                            }

                        }
                      
                    }
                    // 3 4
                    //处理新添加的图片 匹配出新添加的图片 把图片从临时文件夹中移动到Image文件夹中
                    MatchCollection matchs = Regex.Matches(textContent, "(?<=/Document/Temp/).+?(?=\".+?/>)");
                    foreach (Match match in matchs)
                    {
                        string oldPath = Server.MapPath("~/Document/Temp/") + match.Value;
                        string newPath = Server.MapPath("~/Document/Notice/Image/") + match.Value;
                        //移动文件
                        try
                        {
                            System.IO.File.Move(oldPath, newPath);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }

                    //替换所有图片路径
                    textContent = textContent.Replace("/Document/Temp/", "/Document/Notice/Image/");
                    //保存文件 公告内容的txt文件
                    TextWriter textWriter = new StreamWriter(filePath, false, new System.Text.UTF8Encoding(false));
                    textWriter.Write(textContent);
                    textWriter.Close();
                    #endregion

                    #region 1.2.2 更新数据库中公告信息
                    //更新公告信息
                    dbNotice.NoticeTypeDetailID = pwNotice.NoticeTypeDetailID;
                    dbNotice.NoticeName = pwNotice.NoticeName;
                    //dbNotice.ReleaseTime = DateTime.Now;
                    dbNotice.NoticeContent = fileName;
                    // 是否置顶
                    if (pwNotice.Overhead == null)
                    {
                        pwNotice.Overhead = false;
                    }
                    dbNotice.Overhead = pwNotice.Overhead;//是否置顶 没有勾选
                    dbNotice.New = pwNotice.New;
                    myModel.Entry(dbNotice).State = System.Data.Entity.EntityState.Modified;
                    #endregion

                    #endregion
                    #region 1.3 处理附件内容与轮播内容
                    if (myModel.SaveChanges() > 0) {
                        #region 1.3.1 处理附件内容
                        int intNoticeId = pwNotice.NoticeID;
                        //比较:session和oldsession
                        /*
                           得出新增的文件:新增数据,新增文件(temp -> Attachment);
                           得出删除的文件:删除数据,删除文件(Attachment: delete)。
                        */
                        /*获取session中的文件表 1 3 4 */
                        List<FilesVo> sessionFiles = new List<FilesVo>();
                        if (Session["sessionFiles"] != null) //当前session里面的附件信息
                        {
                            sessionFiles = Session["sessionFiles"] as List<FilesVo>;
                        }
                        //获取原来的附件文件列表 1 2 
                        List<FilesVo> oldSessionFiles = new List<FilesVo>();
                        if (Session["oldSessionFiles"] != null)
                        {
                            oldSessionFiles = Session["oldSessionFiles"] as List<FilesVo>;
                        }
                        //现在我们要获取新增的数据 
                        //添加的附件
                        List<FilesVo> addFiles = new List<FilesVo>();//对比session里面的值 找出需要新增的附件
                        if (sessionFiles != null) {
                            foreach (FilesVo filesVo in sessionFiles)
                            {
                                if (!oldSessionFiles.Contains(filesVo))
                                {
                                    addFiles.Add(filesVo);
                                }
                            }
                        }
                        //移除的附件
                        List<FilesVo> deleteFiles = new List<FilesVo>();
                        //对比session里面的值 找出需要删除的附件
                        if (oldSessionFiles != null)
                        {
                            foreach (FilesVo filesVo in oldSessionFiles)
                            {
                                if (!sessionFiles.Contains(filesVo))
                                {
                                    deleteFiles.Add(filesVo);
                                }
                            }
                        }

                        //如果有新添加的
                        if (addFiles.Count > 0)
                        {
                            List<PW_File> listfFiles = new List<PW_File>();
                            for (int i = 0; i < addFiles.Count; i++)
                            {
                                PW_File file = new PW_File() ;
                                file.NoticeID = intNoticeId;
                                file.FileTypeID = addFiles[i].FileTypeID;
                                file.Files = addFiles[i].Files;
                                listfFiles.Add(file);

                                //移动附件
                                string strAttachmentFileName = addFiles[i].FileName;
                                string strAttachmentOldPath = Server.MapPath("~/Document/Temp/") + strAttachmentFileName;
                                string strstrAttachmentNewPath = Server.MapPath("~/Document/Notice/Attachment/") + strAttachmentFileName;
                                try
                                {
                                    System.IO.File.Move(strAttachmentOldPath, strstrAttachmentNewPath);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            }
                            //保存
                            myModel.PW_File.AddRange(listfFiles);
                            myModel.SaveChanges();
                        }
                        //有需要移除的附件
                        if (deleteFiles.Count > 0) {
                            //删除 附件文件夹里面的数据  删除附件表里面的数据
                            string dFilePath = Server.MapPath("~/Document/Notice/Attachment/");
                            List<PW_File> listfFiles = new List<PW_File>();
                            for (int i = 0; i < deleteFiles.Count; i++) {
                                //deleteFiles[i].FileID
                                int FileID = deleteFiles[i].FileID;
                                PW_File file = myModel.PW_File.Single(m => m.FileID == FileID);
                                listfFiles.Add(file);
                                try
                                {
                                    System.IO.File.Delete(dFilePath + deleteFiles[i].FileName);
                                }
                                catch (Exception e)
                                {
                                    Console.WriteLine(e);
                                }
                            }

                            myModel.PW_File.RemoveRange(listfFiles);
                            myModel.SaveChanges();
                        }
                        #endregion
                        #region 1.3.2 处理轮播图片内容
                        //轮播处理思路:判断:之前有没有?,现在有没有?
                        /*
                            1.之前没有,现在有。从无到有 :新增数据,新增文件:重命名文件名 
                            2.之前有,现在没有。从有到无:删除数据,删除文件
                            3.之前有,现在有。替换: 数据库数据修改 ;文件:删除原来图片,新增现在图片*
                        */
                        //能否获取原来的轮播(可能有,可能没有)
                        PW_NoticeCarousel dbNoticeCarousel = (from tbNoticeCarousel in myModel.PW_NoticeCarousel
                                                              where tbNoticeCarousel.NoticeID == intNoticeId
                                                              select tbNoticeCarousel).SingleOrDefault();
                        if (dbNoticeCarousel != default(PW_NoticeCarousel))
                        {
                            //对应第2和3种情况
                            //判断是否勾选了轮播
                            if (noticeCarousel != null && noticeCarousel == "true")
                            {
                                //对应第3种情况:之前有,现在有 (更新操作)
                                //判断是否上传文件
                                if (noticeCarouseImage != null && noticeCarouseImage.ContentLength > 0) {
                                    //删除轮播原来的图片
                                    System.IO.File.Delete(Server.MapPath("~" + dbNoticeCarousel.NoticeCarousel));
                                    //保存新的图片
                                    //文件类型  ;
                                    string imgExtension = Path.GetExtension(noticeCarouseImage.FileName);
                                    //文件名称
                                    string imgFileName = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "-" + Guid.NewGuid() + imgExtension;
                                    //保存文件的路径
                                    string imgFilePath = Server.MapPath("~/Document/Notice/NoticeCarousel/") + imgFileName;
                                    //保存文件
                                    noticeCarouseImage.SaveAs(imgFilePath);

                                    //更新数据库
                                    dbNoticeCarousel.NoticeCarousel = "/Document/Notice/NoticeCarousel/" + imgFileName;
                                    myModel.Entry(dbNoticeCarousel).State = System.Data.Entity.EntityState.Modified;
                                    myModel.SaveChanges();
                                }
                            }
                            else
                            {
                                //对应第2种情况:之前有,现在没有 (删除操作)
                                //删除轮播对应的图片
                                System.IO.File.Delete(Server.MapPath("~" + dbNoticeCarousel.NoticeCarousel));
                                //删除轮播数据
                                myModel.PW_NoticeCarousel.Remove(dbNoticeCarousel);
                                myModel.SaveChanges();
                            }
                        }
                        else {
                            //对应第1中情况:之前没有,现在有
                            if (noticeCarousel != null && noticeCarousel == "true") 
                            {
                                选择了轮播
                                //判断是否上传文件
                                if (noticeCarouseImage != null && noticeCarouseImage.ContentLength > 0)
                                {
                                    //保存文件 
                                    //文件类型
                                    string imgExtension = Path.GetExtension(noticeCarouseImage.FileName);
                                    //文件名称
                                    string imgFileName = DateTime.Now.ToUniversalTime().ToString("yyyy-MM-dd") + "-" + Guid.NewGuid() + imgExtension;
                                    //保存文件的路径
                                    string imgFilePath = Server.MapPath("~/Document/Notice/NoticeCarousel/") + imgFileName;
                                    //保存文件
                                    noticeCarouseImage.SaveAs(imgFilePath);
                                    //新增轮播数据
                                    PW_NoticeCarousel pwNoticeCarousel = new PW_NoticeCarousel();
                                    pwNoticeCarousel.NoticeID = intNoticeId;
                                    pwNoticeCarousel.NoticeCarousel = "/Document/Notice/NoticeCarousel/" + imgFileName;
                                    myModel.PW_NoticeCarousel.Add(pwNoticeCarousel);
                                    myModel.SaveChanges();

                                }
                            }
                        }
                        #endregion
                        msg.State = true;
                        msg.Text = "修改公告成功";
                    }
                    else
                    {
                        msg.Text = "修改失败!";
                    }
                    #endregion
                }
                else {
                    msg.Text = "数据不完整!";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                msg.Text = "数据异常";
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }

        #endregion

可以说修改公告信息的代码比前两个部分加起来的更多。因为需要考虑到的因素比较多,所以代码也比较多,同时还需要对数据回填的数据进行判断。除了回填图片,文本,标签,字体,轮播图之外还需要回填附件。同时也需要判断数据是否存在,不存在则返回“数据不完整”。

第五部分,也是最后一部分,发布公告的文件处理。

文件的处理方式
         一般我们会把文件保存到文件夹里面:这里我们在做发布公告的时候会创建几个文件夹,如下:
        Temp 临时文件夹(上传的文件,在这里临时保存)
        Notice 最终文件夹:
            Attachment附件,
            Image:富文本编辑器图片;
            NoticeCarousel 轮播图片;
            Text:富文本编辑器内容

#region  5.发布公告 文件处理
        /// <summary>
        /// 5.1 发布公告->富文本框 的图片处理
        /// </summary>
        /// <param name="upload"></param>
        /// <returns></returns>
        public ActionResult UpEditorFile(HttpPostedFileBase upload)
        {
            //封装返回数据的实体
            Ckeditor4UploadResult ck = new Ckeditor4UploadResult();
            try
            {
                if (upload != null)
                {
                    //文件类型 如:.png 
                    string fileExtension = Path.GetExtension(upload.FileName);
                    //文件名称
                    string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "-" + Guid.NewGuid() + fileExtension;
                    //检查目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Temp/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Temp/"));
                    }
                    //保存文件的路径
                    string filePath = Server.MapPath("~/Document/Temp/") + fileName;
                    if (fileExtension != null)
                    {
                        fileExtension = fileExtension.ToLower();//小写
                        if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileExtension))
                        {
                            //保存文件
                            upload.SaveAs(filePath);
                            var url = "/Document/Temp/" + fileName;
                            ck.uploaded = 1;//上传cg
                            ck.fileName = fileName;
                            ck.url = url;
                        }
                        else {
                            ck.error.message = "只能上图片";
                        }
                    }
                    else {
                        ck.error.message = "文件类型有问题";
                    }

                }
                else {
                    ck.error.message = "上传文件为空!";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                ck.error.message = "上传失败!";
            }
            return Json(ck,JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 5.2 发布公告-> 上传附加
        /// </summary>
        /// <param name="attachmentFile">附件</param>
        /// <returns></returns>
        public ActionResult UploadAttachment(HttpPostedFileBase attachmentFile)
        {
            ReturnJson msg = new ReturnJson();
            try
            {
                //获取上载文件的大小(以字节为单位)
                if (attachmentFile.ContentLength <= (20 * 1024 * 1024))
                {
                    #region 1.获取session中的文件表
                    //获取session中的文件表
                    List<FilesVo> sessionFiles = new List<FilesVo>();
                    if (Session["sessionFiles"] != null)
                    {
                        sessionFiles = Session["sessionFiles"] as List<FilesVo>;
                    }
                    #endregion
                    #region 2.保存文件 将上传的附件 保存到临时文件夹中
                    //检查目录是否存在,不存在就创建
                    if (!Directory.Exists(Server.MapPath("~/Document/Temp/")))
                    {
                        Directory.CreateDirectory(Server.MapPath("~/Document/Temp/"));
                    }
                    //文件类型
                    string fileExtension = Path.GetExtension(attachmentFile.FileName);
                    //不包含文件扩展名的名称
                    string fileName = Path.GetFileNameWithoutExtension(attachmentFile.FileName);
                    //原始文件名称
                    string oldFileName = attachmentFile.FileName;
                    //文件名称,添加时间字符串,避免文件名称相同
                    fileName = fileName + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss-ffff") + fileExtension;
                    //保存文件的路径
                    string filePath = Server.MapPath("~/Document/Temp/") + fileName;
                    //保存文件
                    attachmentFile.SaveAs(filePath);
                    #endregion
                    #region 3.判断上传文件的类型
                    //文件格式
                    int fileTypeId;//文件类型ID
                    string fileTypeName;//文件类型名称
                    //将文件的扩展名 全部转换成小写 用于进行比较
                    fileExtension = fileExtension.ToLower();
                    if ("(.mp4)|(.avi)|(.flv)|(.rmvb|(.rm)|(.3gp)|(.mkv)|(.dvd)|(.mpg)|(.mov)".Contains(fileExtension))
                    {
                        fileTypeId = 1;//视频
                        fileTypeName = "视频";
                    }
                    else if ("(.mp3)|(.wav)|(.cd)|(.ogg)|(.ape)|(.au)".Contains(fileExtension))
                    {
                        fileTypeId = 2;//音频
                        fileTypeName = "音频";
                    }
                    else if ("(.txt)|(.text)".Contains(fileExtension))
                    {
                        fileTypeId = 3;//文本
                        fileTypeName = "文本";
                    }
                    else if ("(.doc)|(.docx)|(.xls)|(.xlsx)|(.ppt)|(.pptx)".Contains(fileExtension))
                    {
                        fileTypeId = 4;//文档
                        fileTypeName = "文档";
                    }
                    else if ("(.gif)|(.jpg)|(.bmp)|(.jpeg)|(.png)".Contains(fileExtension))
                    {
                        fileTypeId = 5;//图片
                        fileTypeName = "图片";
                    }
                    else
                    {
                        fileTypeId = 7;//其他
                        fileTypeName = "其他";
                    }
                    #endregion
                    #region 4.将上传的文件信息 封装成FilesVo文件对象
                    string strfileName = HttpUtility.UrlEncode(fileName, Encoding.GetEncoding("UTF-8"));
                    FilesVo myFile = new FilesVo()
                    {
                        FileTypeID = fileTypeId,
                        FileTypeName = fileTypeName,
                        FileName = fileName,
                        FileGuid = Guid.NewGuid().ToString("N"),// e0a953c3ee6040eaa9fae2b667060e09 
                        Files = "<a href=\"/SystemManagement/IssuanceNotice/DownloadAttachment?fileName=" + strfileName + "\" target=\"_blank\">" + oldFileName + "</a>"
                        //Files = "<a href=\"/SystemManagement/IssuanceNotice/DownloadAttachment?fileName=" + fileName + "\" target=\"_blank\">" + oldFileName + "</a>"
                    };
                    #endregion
                    #region 5.更新 Session["sessionFiles"]中的数据
                    if (sessionFiles != null)
                    {
                        sessionFiles.Add(myFile);
                        //把上传的附件记录到session
                        Session["sessionFiles"] = sessionFiles;
                        msg.State = true;
                        msg.Text = "文件上传成功!";
                    }
                    #endregion
                }
                else {
                    msg.Text = "上传的文件不能大于20M";
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                msg.Text = "附件上传失败!";
            }
            return Json(msg, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 5.3 发布公告-> table表格显示附件信息(在session中查询数据) 
        /// </summary>
        /// <param name="layuiTablePage">page limit</param>
        /// <returns></returns>
        public ActionResult SelectSessionFiles(LayuiTablePage layuiTablePage)
        { // page 1  limit 10
          //0 ~9
          //用户存放 从Session["sessionFiles"]中获取的数据
            List<FilesVo> sessionFiles = new List<FilesVo>();
            //返回的files列表信息
            List<FilesVo> list = new List<FilesVo>();
            //获取session中的附件文件表
            if (Session["sessionFiles"] != null)
            {
                sessionFiles = Session["sessionFiles"] as List<FilesVo>;
            }
            if (sessionFiles != null)//列表不为空
            {
                // 0~9 endIndex结束的索引位置
                int endIndex = layuiTablePage.GetEndIndex();//9
                if (endIndex >= sessionFiles.Count)// 9>=1
                {
                    //判断的目的是为了 后面循环的时候,不超出数组的取值范围
                    //例如:session中的数据只有2条,但是table表格limit为5,
                    endIndex = sessionFiles.Count - 1;//索引从0开始
                }
                //把表格sessionFiles数据遍历 新增到list
                for (int i = layuiTablePage.GetStartIndex(); i <= endIndex; i++)
                {
                    list.Add(sessionFiles[i]);
                }
            }
            LayuiTableData<FilesVo> layuiTableData = new LayuiTableData<FilesVo>()
            {
                count = sessionFiles.Count,
                data = list
            };
            return Json(layuiTableData, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// 5.4 发布公告 -> 删除附件中的数据
        /// </summary>
        /// <param name="fileGuid"></param>
        /// <returns></returns>
        public ActionResult RemoveAttachmentFile(string fileGuid)
        {
            ReturnJson msg = new ReturnJson();
            try
            {
                //获取session中的附件文件表
                List<FilesVo> sessionFiles = new List<FilesVo>();
                if (Session["sessionFiles"] != null)
                {
                    sessionFiles = Session["sessionFiles"] as List<FilesVo>;
                }
                //移除对应的文件
                if (sessionFiles != null) {

                    foreach (FilesVo item in sessionFiles)
                    {
                        if (item.FileGuid == fileGuid)
                        {
                            sessionFiles.Remove(item);
                            break;
                        }
                    }
                    //更新session
                    Session["sessionFiles"] = sessionFiles;
                    msg.State = true;
                    msg.Text = "删除成功";
                }

            }
            catch (Exception e)
            {
                msg.Text = "删除附件异常";
            }
            return Json(msg, JsonRequestBehavior.AllowGet);

        }
        /// <summary>
        /// 5.5 发布公告--> 下载附件 临时附件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult DownloadAttachment(string fileName) 
        {
            fileName = HttpUtility.UrlDecode(fileName, Encoding.GetEncoding("UTF-8"));
            // 返回Web服务器上对应的物理路径
            string filePath = Server.MapPath("~/Document/Temp/") + fileName;
            if (System.IO.File.Exists(filePath))
            {
                //获取不包含文件扩展名的名称
                //2021前端大纲2021-09-06-10-22-10-7556.xlsx
                //2021前端大纲2021-09-06-10-22-10-7556
                string strfileName = Path.GetFileNameWithoutExtension(filePath);
                //2021前端大纲.xlxs
                strfileName = strfileName.Substring(0, strfileName.Length - 24);
                strfileName= strfileName + Path.GetExtension(filePath);
                //去除文件上传时添加的时间字符串 yyyy-MM-dd-HH-mm-ss-ffff 24位
                //string strfileName = "下载的文件" + Path.GetExtension(filePath);
                return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", strfileName);
            }
            else {
                return Content("下载的文件不存在");
            }
        }
        /// <summary>
        /// 5.6 发布公告--> 下载附件 正式的附件
        /// </summary>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public ActionResult DownloadAttachment2(string fileName)
        {
            //fileName = HttpUtility.UrlDecode(fileName, Encoding.GetEncoding("UTF-8"));
            // 返回Web服务器上对应的物理路径
            string filePath = Server.MapPath("~/Document/Notice/Attachment/") + fileName;
            if (System.IO.File.Exists(filePath))
            {
                //获取不包含文件扩展名的名称
                //2021前端大纲2021-09-06-10-22-10-7556.xlsx
                //2021前端大纲2021-09-06-10-22-10-7556
                string strfileName = Path.GetFileNameWithoutExtension(filePath);
                //2021前端大纲.xlxs
                strfileName = strfileName.Substring(0, strfileName.Length - 24);
                strfileName = strfileName + Path.GetExtension(filePath);
                //去除文件上传时添加的时间字符串 yyyy-MM-dd-HH-mm-ss-ffff 24位
                //string strfileName = "下载的文件" + Path.GetExtension(filePath);
                return File(new FileStream(filePath, FileMode.Open), "application/octet-stream", strfileName);
            }
            else
            {
                return Content("下载的文件不存在");
            }
        }
        #endregion

文件的处理,需要点击文件时,可以下载文件。同时可以在富文本框中添加图片,并处理富文本框中的图片,将富文本框中的图片上传到指定的文件夹中。在table表格中显示附件信息。在新增或修改过程中可以删除附件中的信息。

这五个部分完成后才算是完成了,重邮项目中的发布公告部分。发布公告可以说是重邮项目中代码量比较多的一个部分,不过比起"试题管理"可能只是小kess。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值