public static string GetVirtualPathFormat(string attachmentFolder, IAttachmentFileInfo attachment) { return("{uploads}" + ParseRule(attachmentFolder, attachment.CreatedDate).Replace(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + attachment.Id + attachment.FileType); }
/// <summary>保存附件信息</summary> public static void Upload(IAttachmentFileInfo file) { // ------------------------------------------------------- // 保存 数据库 // 数据库 支持数据库集群 // ------------------------------------------------------- if (AttachmentStorageConfigurationView.Instance.DistributedFileStorageMode == "ON") { DistributedFileInfo param = new DistributedFileInfo(); param.Id = file.Id; param.VirtualPath = file.VirtualPath; param.FileData = file.FileData; AttachmentStorageContext.Instance.AttachmentDistributedFileService.Save(param); } // ------------------------------------------------------- // 保存 二进制数据 // ------------------------------------------------------- string path = UploadPathHelper.CombinePhysicalPath(file.Parent.AttachmentFolder, string.Format("{0}{1}", file.Id, file.FileType)); if (!File.Exists(path)) { UploadPathHelper.TryCreateDirectory(path); ByteHelper.ToFile(file.FileData, path); } }
/// <summary>删除记录</summary> /// <param name="id">标识</param> public void Delete(string id) { if (string.IsNullOrEmpty(id)) { return; } // 01.删除物理文件信息 IAttachmentFileInfo file = FindOne(id); if (file != null) { string path = file.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.PhysicalUploadFolder); if (File.Exists(path)) { File.Delete(path); } } // 02.删除数据库信息 Dictionary <string, object> args = new Dictionary <string, object>(); args.Add("WhereClause", string.Format(" Id IN ('{0}') ", StringHelper.ToSafeSQL(id).Replace(",", "','"))); this.ibatisMapper.Delete(StringHelper.ToProcedurePrefix(string.Format("{0}_Delete", this.tableName)), args); // 03.删除分布式文件数据 DistributedFileStorage.Delete(id); }
// ------------------------------------------------------- // 保存 添加 修改 删除 // ------------------------------------------------------- #region 函数:Save(IAttachmentFileInfo param) /// <summary>保存记录</summary> /// <param name="param"><see cref="IAttachmentFileInfo" />实例详细信息</param> /// <returns><see cref="IAttachmentFileInfo" />实例详细信息</returns> public IAttachmentFileInfo Save(IAttachmentFileInfo param) { if (this.IsExist(param.Id)) { new Exception("The same entity's id already exists. |-_-||"); } this.ibatisMapper.Insert(StringHelper.ToProcedurePrefix(string.Format("{0}_Save", this.tableName)), param); return(param); }
// ------------------------------------------------------- // 保存 删除 // ------------------------------------------------------- #region 函数:Save(AccountInfo param) /// <summary>保存记录</summary> /// <param name="param">实例<see cref="IAttachmentFileInfo"/>详细信息</param> /// <returns>实例<see cref="IAttachmentFileInfo"/>详细信息</returns> public IAttachmentFileInfo Save(IAttachmentFileInfo param) { if (string.IsNullOrEmpty(param.AttachmentName)) { throw new ArgumentNullException("附件名称必填。"); } param.FileType = param.FileType.ToLower(); return(provider.Save(param)); }
// ------------------------------------------------------- // 查询 // ------------------------------------------------------- #region 函数:FindOne(XmlDocument doc) /// <summary>获取详细信息</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string FindOne(XmlDocument doc) { StringBuilder outString = new StringBuilder(); string id = XmlHelper.Fetch("id", doc); IAttachmentFileInfo param = this.service.FindOne(id); outString.Append("{\"data\":" + AjaxUtil.Parse <IAttachmentFileInfo>(param) + ","); outString.Append(MessageObject.Stringify("0", I18n.Strings["msg_query_success"], true) + "}"); return(outString.ToString()); }
/// <summary>物理复制全部附件信息到实体类</summary> /// <param name="param"><see cref="IAttachmentFileInfo" />实例详细信息</param> /// <param name="entityId">实体标识</param> /// <param name="entityClassName">实体类名称</param> /// <returns>新的<see cref="IAttachmentFileInfo" />实例详细信息</returns> public IAttachmentFileInfo Copy(IAttachmentFileInfo param, string entityClassName, string entityId) { IAttachmentParentObject parent = new AttachmentParentObject(); parent.EntityId = entityId; parent.EntityClassName = entityClassName; parent.AttachmentEntityClassName = KernelContext.ParseObjectType(typeof(AttachmentFileInfo)); parent.AttachmentFolder = UploadPathHelper.GetAttachmentFolder(param.VirtualPath, param.FolderRule); IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile(parent, param.AttachmentName, param.FileType, param.FileSize, param.FileData); attachment.Save(); return(attachment); }
/// <summary>删除记录</summary> /// <param name="id">标识</param> public void Delete(string id) { IAccountInfo account = KernelContext.Current.User; if (AppsSecurity.IsAdministrator(account, AttachmentStorageConfiguration.ApplicationName)) { this.provider.Delete(id); } else { IAttachmentFileInfo file = this.FindOne(id); if (file.CreatedBy == account.Id) { this.provider.Delete(id); } } }
/// <summary>获取附件信息</summary> public static byte[] Download(IAttachmentFileInfo file) { DistributedFileInfo param = AttachmentStorageContext.Instance.AttachmentDistributedFileService.FindOne(file.Id); if (param == null) { return(null); } else { string path = file.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.PhysicalUploadFolder); UploadPathHelper.TryCreateDirectory(path); ByteHelper.ToFile(param.FileData, path); return(param.FileData); } }
/// <summary>下载</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public ActionResult Download(string options) { JsonData request = JsonMapper.ToObject(options == null ? "{}" : options); // 实体数据标识 string id = !request.Keys.Contains("id") ? string.Empty : request["id"].ToString(); IAttachmentFileInfo param = AttachmentStorageContext.Instance.AttachmentFileService[id]; if (param == null) { KernelContext.Log.Info("file not found id:" + id); ApplicationError.Write(404); } else { if (param != null && param.FileData == null) { KernelContext.Log.Info("file data is null id:" + id); // 下载分布式文件数据 param.FileData = DistributedFileStorage.Download(param); } // [容错] 由于人为原因将服务器上的文件删除。 if (param.FileData == null) { ApplicationError.Write(404); } Response.ContentType = "application/octet-stream"; Response.AddHeader("Content-Disposition", "attachment;filename=" + EncodeFileName(param.AttachmentName)); Response.BinaryWrite(param.FileData); } Response.End(); return(Content(string.Empty)); }
/// <summary>还原附件信息</summary> public void Restore(string id) { IAttachmentFileInfo temp = AttachmentStorageContext.Instance.AttachmentFileService.FindOne(id); this.Id = temp.Id; this.EntityId = temp.EntityId; this.EntityClassName = temp.EntityClassName; this.Parent.AttachmentFolder = temp.VirtualPath.Substring(0, temp.VirtualPath.IndexOf("/")).Replace("{uploads}", ""); this.Parent.AttachmentEntityClassName = KernelContext.ParseObjectType(typeof(AttachmentFileInfo)); this.AttachmentName = temp.AttachmentName; this.VirtualPath = temp.VirtualPath; this.FolderRule = temp.FolderRule; this.FileType = temp.FileType; this.FileSize = temp.FileSize; this.FileData = null; this.FileStatus = temp.FileStatus; this.CreatedBy = temp.CreatedBy; this.CreatedDate = temp.CreatedDate; }
/// <summary>获取分页内容</summary> /// <param name="doc">Xml 文档对象</param> /// <returns>返回操作结果</returns> public string Download(XmlDocument doc) { this.ProcessRequest(HttpContext.Current); string id = HttpContext.Current.Request.QueryString["id"]; IAttachmentFileInfo param = AttachmentStorageContext.Instance.AttachmentFileService[id]; if (param == null) { ApplicationError.Write(404); } else { if (param != null && param.FileData == null) { // 下载分布式文件数据 param.FileData = DistributedFileStorage.Download(param); } // [容错] 由于人为原因将服务器上的文件删除。 if (param.FileData == null) { ApplicationError.Write(404); } HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment;filename=" + EncodeFileName(param.AttachmentName)); HttpContext.Current.Response.BinaryWrite(param.FileData); } HttpContext.Current.Response.End(); return(string.Empty); }
/// <summary>创建附件</summary> /// <param name="applicationName"></param> /// <param name="fileName"></param> /// <returns></returns> public static IAttachmentFileInfo CreateAttachmentFile(IAttachmentParentObject parent, string attachmentId, string attachmentName, string fileType, int fileSize, byte[] fileData) { // 创建对象构建器(Spring.NET) string springObjectFile = AttachmentStorageConfigurationView.Instance.Configuration.Keys["SpringObjectFile"].Value; SpringObjectBuilder objectBuilder = SpringObjectBuilder.Create(AttachmentStorageConfiguration.ApplicationName, springObjectFile); // 创建数据服务对象 IAttachmentFileInfo param = objectBuilder.GetObject <IAttachmentFileInfo>(typeof(IAttachmentFileInfo), new object[] { parent }); param.Id = string.IsNullOrEmpty(attachmentId) ? NewIdentity() : attachmentId; param.AttachmentName = attachmentName; param.FileType = fileType; param.FileSize = fileSize; param.FileData = fileData; param.CreatedDate = DateTime.Now; // 虚拟路径需要创建时间和文件类型参数 param.VirtualPath = UploadPathHelper.GetVirtualPathFormat(parent.AttachmentFolder, param); param.FolderRule = AttachmentStorageConfigurationView.Instance.PhysicalUploadFolderRule; return(param); }
public override void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; try { HttpPostedFile file = request.Files["fileData"]; // 输出类型 id uri base64 string outputType = request.Form["outputType"]; string attachmentId = request.Form["attachmentId"]; string entityId = request.Form["entityId"]; string entityClassName = request.Form["entityClassName"]; string attachmentEntityClassName = request.Form["attachmentEntityClassName"]; string attachmentFolder = request.Form["attachmentFolder"]; // 匿名用户上传文件的文件, 存放在 anonymous 目录 if (KernelContext.Current.User == null) { attachmentFolder = "anonymous"; } // IAttachmentParentObject parent = new AttachmentParentObject(entityId, entityClassName, attachmentEntityClassName, attachmentFolder); IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile( entityId, entityClassName, attachmentEntityClassName, attachmentFolder, file); // Office 在线客户端上传方式 // 支持客户端赋值附件标识 if (!string.IsNullOrEmpty(attachmentId)) { if (AttachmentStorageContext.Instance.AttachmentFileService.IsExist(attachmentId)) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment id already exists."; HttpContext.Current.Response.End(); } else { attachment.Id = attachmentId; } } // 检测文件最小限制 if (attachment.FileSize < AttachmentStorageConfigurationView.Instance.AllowMinFileSize) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file size is too small."; HttpContext.Current.Response.End(); } // 检测文件最大限制 if (attachment.FileSize > AttachmentStorageConfigurationView.Instance.AllowMaxFileSize) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file size is too big."; HttpContext.Current.Response.End(); } // 检测文件名后缀限制 if (!Regex.IsMatch(attachment.FileType, AttachmentStorageConfigurationView.Instance.AllowFileTypes)) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file type is invalid."; HttpContext.Current.Response.End(); } if (HttpContext.Current.Response.StatusCode != 500) { attachment.Save(); KernelContext.Log.Info("attachment id: " + attachment.Id); HttpContext.Current.Response.StatusCode = 200; if (outputType == "uri") { // 输出 uri HttpContext.Current.Response.Write(attachment.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.VirtualUploadFolder)); } else { // 输出 id HttpContext.Current.Response.Write(attachment.Id); } } } catch (Exception ex) { // If any kind of error occurs return a 500 Internal Server error HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "An error occured"; HttpContext.Current.Response.End(); KernelContext.Log.Error(ex.Message, ex); } }
public override void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; string fileName = request.QueryString["fileName"] == null ? string.Empty : request.QueryString["fileName"]; string id = request.QueryString["id"] == null ? string.Empty : request.QueryString["id"]; int targetWidth = request.QueryString["targetWidth"] == null ? 100 : Convert.ToInt32(request.QueryString["targetWidth"]); int targetHeight = request.QueryString["targetHeight"] == null ? 100 : Convert.ToInt32(request.QueryString["targetHeight"]); string attachmentEntityClassName = request.QueryString["attachmentEntityClassName"] == null ? "X3Platform.AttachmentStorage.AttachmentFileInfo" : request.QueryString["attachmentEntityClassName"]; if (string.IsNullOrEmpty(fileName)) { // 以参数形式生成图片 if (!string.IsNullOrEmpty(id)) { // 读取附件原始信息 IAttachmentFileInfo attachment = (IAttachmentFileInfo)SpringContext.Instance.Application.GetObject(attachmentEntityClassName);; attachment.Restore(id); if (attachment.FileData == null) { response.StatusCode = 404; response.Write("Not Found"); return; } string defaultThumbnail = string.Format("{0}_{1}x{2}", attachment.FileType.Replace(".", ""), targetWidth, targetHeight); if (AttachmentStorageConfigurationView.Instance.DefaultThumbnails.IndexOf(defaultThumbnail) > -1) { response.Redirect(AttachmentStorageConfigurationView.Instance.VirtualUploadFolder + "thumbnails/" + defaultThumbnail + ".png"); response.End(); } fileName = string.Format("{0}_{1}x{2}{3}", id, targetWidth, targetHeight, attachment.FileType); Stream stream = ByteHelper.ToStream(attachment.FileData); // 创建缩略图 ThumbnailManagement.CreateThumbnail(id, stream, attachment.FileType, targetWidth, targetHeight); } } else { // 直接以文件名方式访问 if (!ThumbnailManagement.IsExist(fileName)) { response.StatusCode = 404; response.Write("Not Found"); return; } } response.Redirect(AttachmentStorageConfigurationView.Instance.VirtualUploadFolder + "thumbnails/" + fileName); }
public override void ProcessRequest(HttpContext context) { HttpRequest request = context.Request; HttpResponse response = context.Response; try { HttpPostedFile file = request.Files["fileData"]; // 输出类型 id uri base64 string outputType = request.Form["outputType"]; string attachmentId = request.Form["attachmentId"]; string entityId = request.Form["entityId"]; string entityClassName = request.Form["entityClassName"]; string attachmentEntityClassName = request.Form["attachmentEntityClassName"]; string attachmentFolder = request.Form["attachmentFolder"]; // 调整图片大小 int resize = request.Form["resize"] == null ? 0 : Convert.ToInt32(request.Form["resize"]); int targetWidth = request.Form["targetWidth"] == null ? 0 : Convert.ToInt32(request.Form["targetWidth"]); int targetHeight = request.Form["targetHeight"] == null ? 0 : Convert.ToInt32(request.Form["targetHeight"]); // 设置图片缩略图 int thumbnail = request.Form["thumbnail"] == null ? 0 : Convert.ToInt32(request.Form["thumbnail"]); int thumbnailWidth = request.QueryString["targetWidth"] == null ? 100 : Convert.ToInt32(request.QueryString["thumbnailWidth"]); int thumbnailHeight = request.QueryString["thumbnailHeight"] == null ? 100 : Convert.ToInt32(request.QueryString["thumbnailHeight"]); // 匿名用户上传文件的文件, 存放在 anonymous 目录 if (KernelContext.Current.User == null) { attachmentFolder = "anonymous"; } IAttachmentFileInfo attachment = UploadFileHelper.CreateAttachmentFile( entityId, entityClassName, attachmentEntityClassName, attachmentFolder, file); // Office 在线客户端上传方式 // 支持客户端赋值附件标识 if (!string.IsNullOrEmpty(attachmentId)) { if (AttachmentStorageContext.Instance.AttachmentFileService.IsExist(attachmentId)) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment id already exists."; HttpContext.Current.Response.End(); } else { attachment.Id = attachmentId; } } // 检测文件最小限制 if (attachment.FileSize < AttachmentStorageConfigurationView.Instance.AllowMinFileSize) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file size is too small."; HttpContext.Current.Response.End(); } // 检测文件最大限制 if (attachment.FileSize > AttachmentStorageConfigurationView.Instance.AllowMaxFileSize) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file size is too big."; HttpContext.Current.Response.End(); } // 检测文件名后缀限制 if (!Regex.IsMatch(attachment.FileType, AttachmentStorageConfigurationView.Instance.AllowFileTypes)) { HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "Attachment file type is invalid."; HttpContext.Current.Response.End(); } if (HttpContext.Current.Response.StatusCode != 500) { // 调整图片大小 if (resize == 1) { Image image = Image.FromStream(ByteHelper.ToStream(attachment.FileData)); attachment.FileData = ThumbnailManagement.Resize(image, attachment.FileType, targetWidth, targetHeight); } if (outputType == "base64") { // 输出 Base64 HttpContext.Current.Response.StatusCode = 200; HttpContext.Current.Response.Write(ByteHelper.ToBase64(attachment.FileData)); } else { attachment.Save(); // 调整图片大小 if (thumbnail == 1) { Image image = Image.FromStream(ByteHelper.ToStream(attachment.FileData)); attachment.FileData = ThumbnailManagement.Resize(image, attachment.FileType, thumbnailWidth, thumbnailHeight); var fileName = string.Format("{0}_{1}x{2}{3}", attachment.Id, thumbnailWidth, thumbnailHeight, attachment.FileType); Stream stream = ByteHelper.ToStream(attachment.FileData); // 创建缩略图 ThumbnailManagement.CreateThumbnail(attachment.Id, stream, attachment.FileType, thumbnailWidth, thumbnailHeight); } HttpContext.Current.Response.StatusCode = 200; if (outputType == "uri") { // 输出 uri HttpContext.Current.Response.Write(attachment.VirtualPath.Replace("{uploads}", AttachmentStorageConfigurationView.Instance.VirtualUploadFolder)); } else { // 输出 id HttpContext.Current.Response.Write(attachment.Id); } } } } catch (Exception ex) { // If any kind of error occurs return a 500 Internal Server error HttpContext.Current.Response.StatusCode = 500; HttpContext.Current.Response.StatusDescription = "An error occured"; HttpContext.Current.Response.End(); KernelContext.Log.Error(ex.Message, ex); } }
/// <summary>物理移动附件路径</summary> /// <param name="param">实例<see cref="IAttachmentFileInfo"/>详细信息</param> /// <param name="entityId">实体标识</param> /// <param name="entityClassName">实体类名称</param> /// <returns>新的 实例<see cref="IAttachmentFileInfo"/>详细信息</returns> public IAttachmentFileInfo Move(IAttachmentFileInfo param, string path) { throw new NotImplementedException(); }