예제 #1
0
        /// <summary>
        /// 保存表单附件
        /// </summary>
        /// <param name="moduleId">模块Id</param>
        /// <param name="id">记录Id</param>
        /// <param name="fileMsg">文件信息</param>
        /// <param name="isAdd">是否只是添加</param>
        /// <returns></returns>
        public ActionResult SaveFormAttach(Guid moduleId, Guid id, string fileMsg, bool isAdd = false)
        {
            if (string.IsNullOrEmpty(fileMsg))
            {
                return(Json(new ReturnResult {
                    Success = true, Message = string.Empty
                }));
            }
            if (_Request == null)
            {
                _Request = Request;
            }
            SetRequest(_Request);
            string errMsg = string.Empty;
            List <AttachFileInfo> addAttachs = null;

            try
            {
                string pathFlag = "\\";
                if (WebConfigHelper.GetAppSettingValue("IsLinux") == "true")
                {
                    pathFlag = "/";
                }
                UserInfo              currUser   = GetCurrentUser(_Request);
                Guid?                 userId     = currUser != null ? currUser.UserId : (Guid?)null;
                string                userName   = currUser != null ? currUser.UserName : string.Empty;
                Sys_Module            module     = SystemOperate.GetModuleById(moduleId);
                List <AttachFileInfo> attachInfo = JsonHelper.Deserialize <List <AttachFileInfo> >(HttpUtility.UrlDecode(fileMsg, Encoding.UTF8));
                #region  除已经移除的附件
                if (!isAdd) //非新增状态
                {
                    List <Guid> existIds = new List <Guid>();
                    if (attachInfo != null && attachInfo.Count > 0)
                    {
                        existIds = attachInfo.Select(x => x.Id.ObjToGuid()).Where(x => x != Guid.Empty).ToList();
                    }
                    //对已删除的附件进行处理
                    List <Sys_Attachment> tempAttachments = CommonOperate.GetEntities <Sys_Attachment>(out errMsg, x => x.Sys_ModuleId == moduleId && x.RecordId == id, null, false);
                    if (tempAttachments != null)
                    {
                        tempAttachments = tempAttachments.Where(x => !existIds.Contains(x.Id)).ToList();
                    }
                    SystemOperate.DeleteAttachment(tempAttachments);
                }
                #endregion
                #region 添加附件
                if (attachInfo != null && attachInfo.Count > 0)
                {
                    addAttachs = new List <AttachFileInfo>();
                    //日期文件夹
                    string dateFolder = DateTime.Now.ToString("yyyyMM", DateTimeFormatInfo.InvariantInfo);
                    //记录对应的titleKey值
                    string titleKeyValue       = CommonOperate.GetModelTitleKeyValue(moduleId, id);
                    List <Sys_Attachment> list = new List <Sys_Attachment>();
                    foreach (AttachFileInfo info in attachInfo)
                    {
                        if (string.IsNullOrEmpty(info.AttachFile))
                        {
                            continue;
                        }
                        if (info.Id.ObjToGuid() != Guid.Empty)
                        {
                            continue;                                                                              //原来的附件
                        }
                        string oldAttchFile = _Request.RequestContext.HttpContext.Server.MapPath(info.AttachFile); //临时附件
                        string dir          = string.Format("{0}Upload{3}Attachment{3}{1}{3}{2}", Globals.GetWebDir(), module.TableName, dateFolder, pathFlag);
                        if (!Directory.Exists(dir))                                                                //目录不存在则创建
                        {
                            Directory.CreateDirectory(dir);
                        }
                        string newAttachFile = string.Format("{0}{4}{1}_{2}{3}", dir, Path.GetFileNameWithoutExtension(info.FileName), id, Path.GetExtension(info.FileName), pathFlag);
                        try
                        {
                            System.IO.File.Copy(oldAttchFile, newAttachFile, true); //复制文件
                        }
                        catch (Exception ex)
                        {
                            return(Json(new ReturnResult {
                                Success = false, Message = ex.Message
                            }, "text/plain"));
                        }
                        //文件复制完成后删除临时文件
                        try
                        {
                            System.IO.File.Delete(oldAttchFile);
                        }
                        catch { }
                        string newPdfFile = string.Empty; //pdf文件
                        string newSwfFile = string.Empty; //swf文件
                        //可以转换成swf的进行转换
                        if (info.FileType.Equals(".doc") || info.FileType.Equals(".docx") ||
                            info.FileType.Equals(".xls") || info.FileType.Equals(".xlsx") ||
                            info.FileType.Equals(".ppt") || info.FileType.Equals(".pptx") ||
                            info.FileType.Equals(".pdf"))
                        {
                            newPdfFile = string.Format("{0}{2}{1}.pdf", dir, Path.GetFileNameWithoutExtension(newAttachFile), pathFlag);
                            newSwfFile = string.Format("{0}{2}{1}.swf", dir, Path.GetFileNameWithoutExtension(newAttachFile), pathFlag);
                            string   exePath = _Request.RequestContext.HttpContext.Server.MapPath("~/bin/SWFTools/pdf2swf.exe");
                            string   binPath = _Request.RequestContext.HttpContext.Server.MapPath("~/bin/");
                            string[] obj     = new string[] { info.FileType, newAttachFile, newPdfFile, newSwfFile, exePath, binPath };
                            CreateSwfFile(obj);
                        }
                        //构造文件URL,保存为相对URL地址
                        string fileUrl   = string.Format("Upload/Attachment/{0}/{1}/{2}", module.TableName, dateFolder, Path.GetFileName(newAttachFile));
                        string pdfUrl    = string.IsNullOrEmpty(newPdfFile) ? string.Empty : newPdfFile.Replace(Globals.GetWebDir(), string.Empty).Replace("\\", "/");
                        string swfUrl    = string.IsNullOrEmpty(newSwfFile) ? string.Empty : newSwfFile.Replace(Globals.GetWebDir(), string.Empty).Replace("\\", "/");
                        Guid   attachiId = Guid.NewGuid();
                        info.Id = attachiId.ToString();
                        list.Add(new Sys_Attachment()
                        {
                            Id                  = attachiId,
                            Sys_ModuleId        = moduleId,
                            Sys_ModuleName      = module.Name,
                            RecordId            = id,
                            RecordTitleKeyValue = titleKeyValue,
                            FileName            = info.FileName,
                            FileType            = info.FileType,
                            FileSize            = info.FileSize,
                            FileUrl             = fileUrl,
                            PdfUrl              = pdfUrl,
                            SwfUrl              = swfUrl,
                            AttachType          = info.AttachType,
                            CreateDate          = DateTime.Now,
                            CreateUserId        = userId,
                            CreateUserName      = userName,
                            ModifyDate          = DateTime.Now,
                            ModifyUserId        = userId,
                            ModifyUserName      = userName
                        });
                        string tempUrl = "/" + fileUrl;
                        if (!string.IsNullOrEmpty(swfUrl))
                        {
                            tempUrl = string.Format("/Page/DocView.html?fn={0}&swfUrl={1}", HttpUtility.UrlEncode(info.FileName).Replace("+", "%20"), HttpUtility.UrlEncode(swfUrl).Replace("+", "%20"));
                        }
                        info.AttachFile = tempUrl;
                        info.PdfFile    = pdfUrl;
                        info.SwfFile    = swfUrl;
                        addAttachs.Add(info);
                    }
                    if (list.Count > 0)
                    {
                        Guid attachModuleId = SystemOperate.GetModuleIdByName("附件信息");
                        bool rs             = CommonOperate.OperateRecords(attachModuleId, list, ModelRecordOperateType.Add, out errMsg, false);
                        if (!rs)
                        {
                            addAttachs = null;
                        }
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                errMsg = ex.Message;
            }
            return(Json(new { Success = string.IsNullOrEmpty(errMsg), Message = errMsg, AddAttachs = addAttachs }, "text/plain"));
        }