/// <summary> /// 保存表单附件 /// </summary> /// <param name="moduleId">模块Id</param> /// <param name="id">记录Id</param> /// <param name="fileMsg">文件信息</param> /// <param name="isAdd">是否只是添加</param> /// <returns></returns> public JsonResult 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 = System.IO.Path.DirectorySeparatorChar.ToString(); 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 = WebHelper.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 })); } //文件复制完成后删除临时文件 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 = WebHelper.MapPath("~/bin/SWFTools/pdf2swf.exe"); string binPath = WebHelper.MapPath("~/bin/"); string[] obj = new string[] { info.FileType, newAttachFile, newPdfFile, newSwfFile, exePath, binPath }; SystemOperate.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(pathFlag, "/"); string swfUrl = string.IsNullOrEmpty(newSwfFile) ? string.Empty : newSwfFile.Replace(Globals.GetWebDir(), string.Empty).Replace(pathFlag, "/"); Guid attachiId = Guid.NewGuid(); info.Id = attachiId.ToString(); if (string.IsNullOrEmpty(pdfUrl) && !string.IsNullOrEmpty(fileUrl) && info.FileType.Equals(".pdf")) { pdfUrl = fileUrl; } 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 })); }
/// <summary> /// 上传附件,兼容非表单附件 /// </summary> /// <param name="file">文件</param> /// <returns></returns> public JsonResult UploadAttachment(IFormFileCollection file) { if (file == null || file.Count() == 0) { return(Json(new ReturnResult { Success = false, Message = "请选择上传文件!" })); } if (_Request == null) { _Request = Request; } SetRequest(_Request); Guid? moduleId = _Request.QueryEx("moduleId").ObjToGuidNull(); //模块Id,针对表单附件 Guid? id = _Request.QueryEx("id").ObjToGuidNull(); //记录Id,针对表单附件 bool isCreateSwf = _Request.QueryEx("isCreateSwf").ObjToBool(); //是否创建SWF文件 string attachType = _Request.QueryEx("attachType").ObjToStr(); //附件类型 string message = string.Empty; StringBuilder msg = new StringBuilder(); List <AttachFileInfo> fileMsg = new List <AttachFileInfo>(); foreach (var item in file) { try { string fileSize = FileOperateHelper.FileSize(item.Length); string fileType = Path.GetExtension(item.FileName); string fileName = item.FileName; string pathFlag = System.IO.Path.DirectorySeparatorChar.ToString(); int s = fileName.LastIndexOf(pathFlag); if (s >= 0) { fileName = fileName.Substring(s + 1); } //保存文件 string filePath = string.Empty; if (moduleId.HasValue) //表单附件 { filePath = UploadFileManager.SaveAs(item, "Attachment", "Temp"); } else { filePath = UploadFileManager.SaveAs(item, "Temp"); } filePath = filePath.StartsWith("~/") ? filePath : filePath.StartsWith("/") ? "~" + filePath : "~/" + filePath; //swf保存路径 string swfPath = string.Empty; //pdf保存路径 string pdfPath = string.Empty; if (isCreateSwf && !moduleId.HasValue) { //exe路径 string exePath = WebHelper.MapPath("~/bin/SWFTools/pdf2swf.exe"); //bin路径 string binPath = WebHelper.MapPath("~/bin/"); if (fileType.Equals(".doc") || fileType.Equals(".docx") || fileType.Equals(".xls") || fileType.Equals(".xlsx") || fileType.Equals(".ppt") || fileType.Equals(".pptx") || fileType.Equals(".pdf")) { //取pdf和swf路径 SystemOperate.GetSwfFilePath(out pdfPath, out swfPath); //参数 string[] obj = new string[] { fileType, WebHelper.MapPath(filePath), WebHelper.MapPath(pdfPath), WebHelper.MapPath(swfPath), exePath, binPath }; SystemOperate.CreateSwfFile(obj); } } fileMsg.Add(new AttachFileInfo() { AttachFile = filePath, PdfFile = pdfPath, SwfFile = swfPath, FileName = fileName, FileType = fileType, FileSize = fileSize, AttachType = attachType }); } catch (Exception ex) { msg.AppendLine(item.FileName + "上传失败:" + ex.Message); break; } } if (moduleId.HasValue && moduleId.Value != Guid.Empty && id.HasValue && id.Value != Guid.Empty) //查看页面,直接保存附件 { return(SaveFormAttach(moduleId.Value, id.Value, JsonHelper.Serialize(fileMsg), true)); } return(Json(new { Success = string.IsNullOrEmpty(msg.ToString()), Message = string.IsNullOrEmpty(msg.ToString()) ? "上传成功" : msg.ToString(), FileMsg = fileMsg.Count > 0 ? JsonHelper.Serialize(fileMsg) : string.Empty })); }