/// <summary> /// Uploadify的Helper方法用于附件 /// </summary> /// <param name="htmlHelper"></param> /// <param name="name">名称</param> /// <param name="tenantTypeId">租户类型Id</param> /// <param name="allowedFileExtensions">允许的文件类型 /// 格式为(jpg,jpeg,gif)</param> /// <param name="buttonOptions">指定按钮属性的类</param> /// <param name="uploadFileOptions">指定上传配置类</param> /// <returns></returns> public static MvcHtmlString Uploadify(this HtmlHelper htmlHelper, string name, string tenantTypeId, string allowedFileExtensions = "", ButtonOptions buttonOptions = null, UploadFileOptions uploadFileOptions = null) { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(tenantTypeId)) { throw new ExceptionFacade("参数不能为空"); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); if (tenantAttachmentSettings == null) { throw new ExceptionFacade("找不到附件配置"); } if (uploadFileOptions != null && string.IsNullOrEmpty(uploadFileOptions.UploaderUrl)) { uploadFileOptions.MergeUploadifyFormData("tenantTypeId", tenantTypeId); string fileobjName = string.IsNullOrEmpty(uploadFileOptions.FileObjName) ? "Filedata" : uploadFileOptions.FileObjName; uploadFileOptions.MergeUploadifyFormData("requestName", fileobjName); uploadFileOptions.MergeUploadifyFormData("associateId", uploadFileOptions.AssociateId); } if (uploadFileOptions == null) { uploadFileOptions = new UploadFileOptions(); uploadFileOptions.MergeUploadifyFormData("tenantTypeId", tenantTypeId); uploadFileOptions.MergeUploadifyFormData("requestName", "Filedata"); uploadFileOptions.MergeUploadifyFormData("associateId", 0); } if (string.IsNullOrEmpty(allowedFileExtensions)) { return(Uploadify(htmlHelper, name, tenantAttachmentSettings.AllowedFileExtensions, tenantAttachmentSettings.MaxAttachmentLength, uploadFileOptions, buttonOptions)); } else { return(Uploadify(htmlHelper, name, allowedFileExtensions, tenantAttachmentSettings.MaxAttachmentLength, uploadFileOptions, buttonOptions)); } }
/// <summary> /// 输出html编辑器产生的内容,根据显示区域的宽度自动调整图片尺寸,并引入js脚本 /// </summary> /// <param name="htmlHelper"></param> /// <param name="tenantTypeId">租户类型id</param> /// <param name="content">html编辑器的内容</param> /// <param name="imageWidth">显示区域的图片宽度</param> /// <returns></returns> public static MvcHtmlString DisplayHtmlEditorContent(this HtmlHelper htmlHelper, string tenantTypeId, string content, int imageWidth) { if (string.IsNullOrEmpty(content)) { return(MvcHtmlString.Create(string.Empty)); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); content = content.Replace("width=\"" + tenantAttachmentSettings.InlinedImageWidth + "\"", "width=\"" + imageWidth + "\""); content += @"<script> $(function () { SyntaxHighlighter.defaults['toolbar'] = false; SyntaxHighlighter.all(); $(" + "\"a[rel='fancybox']\"" + @").fancybox({ 'transitionIn': 'elastic', 'transitionOut': 'elastic', 'speedIn': 600, 'speedOut': 200 }); }); </script> "; return(MvcHtmlString.Create(content)); }
public ActionResult _Create_UploadImages(string spaceKey) { //reply:已修改 ViewData["TenantAttachmentSettings"] = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Microblog()); return(View()); }
/// <summary> /// 构造函数 /// </summary> /// <param name="tenantTypeId">租户类型Id</param> public AttachmentService(string tenantTypeId) { this.attachmentRepository = new AttachmentRepository <T>(); this.TenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); if (this.TenantAttachmentSettings == null) { throw new ExceptionFacade("没有注册租户附件设置"); } this.StoreProvider = DIContainer.ResolveNamed <IStoreProvider>(this.TenantAttachmentSettings.StoreProviderName); }
/// <summary> /// 删除照片 /// </summary> /// <remarks> /// 1.更新所属相册计数PhotoCount-1 /// 2.更新用户内容计数OwnerData-1 /// 3.如果照片是封面,需要将相册的CoverId属性重置为0 /// 4.需要调用TagService.ClearTagsFromItem删除标签关联 /// 5.需要同步删除照片圈人 /// 6.通过EventModule处理动态和积分的变化; /// 7.需要触发的事件:1)Delete的OnBefore、OnAfter;2)审核状态变更 /// </remarks> /// <param name="photo">照片对象</param> public void DeletePhoto(Photo photo) { //删除与标签的关联 TagService tagService = new TagService(TenantTypeIds.Instance().Photo()); tagService.ClearTagsFromItem(photo.PhotoId, photo.UserId); //删除照片推荐 RecommendService recommendService = new RecommendService(); recommendService.Delete(photo.PhotoId, TenantTypeIds.Instance().Photo()); //相册计数PhotoCount-1及封面 Album album = photo.Album; album.PhotoCount--; if (photo.PhotoId == album.CoverId) { album.CoverId = 0; } albumRepository.Update(album); //删除圈人 IEnumerable <PhotoLabel> photoLabels = this.GetLabelsOfPhoto(null, photo.PhotoId); foreach (PhotoLabel photolabel in photoLabels) { photoLabelRepository.Delete(photolabel); } //删除照片磁盘物理文件 if (!string.IsNullOrEmpty(photo.RelativePath)) { TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Photo()); IStoreProvider storeProvider = DIContainer.ResolveNamed <IStoreProvider>(tenantAttachmentSettings.StoreProviderName); string relativePath = storeProvider.GetRelativePath(photo.RelativePath, true); string fileName = photo.RelativePath.Remove(0, relativePath.Length).Trim('\\').Trim('/'); storeProvider.DeleteFiles(relativePath, fileName); } photoRepository.Delete(photo); EventBus <Photo> .Instance().OnBefore(photo, new CommonEventArgs(EventOperationType.Instance().Delete())); //用户内容计数OwnerData-1 OwnerDataService ownerDataService = new OwnerDataService(TenantTypeIds.Instance().User()); ownerDataService.Change(photo.UserId, OwnerDataKeys.Instance().PhotoCount(), -1); //通过EventModule处理动态和积分的变化; EventBus <Photo> .Instance().OnAfter(photo, new CommonEventArgs(EventOperationType.Instance().Delete())); EventBus <Photo, AuditEventArgs> .Instance().OnAfter(photo, new AuditEventArgs(photo.AuditStatus, null)); }
/// <summary> /// 照片上传 /// </summary> /// <param name="photo">照片对象</param> /// <param name="file">需上传的文件</param> private void UploadPhoto(Photo photo, HttpPostedFileBase file) { if (file == null) { throw new ExceptionFacade("请上传文件"); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Photo()); //验证图片类型 if (!tenantAttachmentSettings.ValidateFileExtensions(file.FileName)) { throw new ExceptionFacade(string.Format("只允许上传后缀名为{0}的文件", tenantAttachmentSettings.AllowedFileExtensions)); } //验证图片大小 if (!tenantAttachmentSettings.ValidateFileLength(file.ContentLength)) { throw new ExceptionFacade(string.Format("文件大小不允许超过{0}", tenantAttachmentSettings.MaxAttachmentLength)); } IStoreProvider storeProvider = DIContainer.ResolveNamed <IStoreProvider>(tenantAttachmentSettings.StoreProviderName); //根据AlbumId生成图片存储路径和新的文件名 string idString = photo.AlbumId.ToString().PadLeft(15, '0'); string relativePath = storeProvider.JoinDirectory(tenantAttachmentSettings.TenantAttachmentDirectory, idString.Substring(0, 5), idString.Substring(5, 5), idString.Substring(10, 5)); string extension = file.FileName.Substring(file.FileName.LastIndexOf('.') + 1).ToLower(); string fileName = string.Format("{0}.{1}", Guid.NewGuid().ToString("N"), extension); //上传原始图片 using (Stream stream = file.InputStream) { storeProvider.AddOrUpdateFile(relativePath, fileName, stream); if (extension != "gif") { //根据设置生成不同尺寸的图片 if (tenantAttachmentSettings.ImageSizeTypes != null) { foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes) { Stream resizedStream = ImageProcessor.Resize(stream, imageSizeType.Size.Width, imageSizeType.Size.Height, imageSizeType.ResizeMethod); storeProvider.AddOrUpdateFile(relativePath, storeProvider.GetSizeImageName(fileName, imageSizeType.Size, imageSizeType.ResizeMethod), resizedStream); if (resizedStream != stream) { resizedStream.Dispose(); } } } } } photo.RelativePath = relativePath + "\\" + fileName; }
/// <summary> /// 设置不同尺寸的图片(附件中) /// </summary> /// <param name="attachment">附件</param> private void SetResizedAttachmentImage(Attachment attachment) { TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(attachment.TenantTypeId); if (tenantAttachmentSettings != null && tenantAttachmentSettings.ImageSizeTypes != null && tenantAttachmentSettings.ImageSizeTypes.Count > 0) { foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes) { IStoreFile file = storeProvider.GetResizedImage(attachment.GetRelativePath(), attachment.FileName, imageSizeType.Size, imageSizeType.ResizeMethod); } } }
public ActionResult _Create_UploadImages(string spaceKey) { //reply:已修改 ViewData["TenantAttachmentSettings"] = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Microblog()); //reply:已修改 IUser user = UserContext.CurrentUser; string tenantTypeId = TenantTypeIds.Instance().Microblog(); IEnumerable <Attachment> attachments = attachmentService.GetTemporaryAttachments(user.UserId, tenantTypeId); if (attachments != null && attachments.Count() > 0) { ViewData["IsHasAttachments"] = true; } return(View()); }
/// <summary> /// 重建缩略图 /// </summary> /// <param name="tenantTypeId">租户类型id</param> /// <returns></returns> public ActionResult _RebuildingThumbnails(string tenantTypeId) { TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); IStoreProvider storeProvider = DIContainer.Resolve <IStoreProvider>(); if (tenantAttachmentSettings == null) { return(Content(string.Empty)); } string path = WebUtility.GetPhysicalFilePath(Path.Combine(storeProvider.StoreRootPath, tenantAttachmentSettings.TenantAttachmentDirectory)); ResetThumbnails(path, tenantAttachmentSettings); //重建缩略图的代码 return(Redirect(SiteUrls.Instance().ControlPanelSuccess("执行成功", SiteUrls.Instance().RebuildingThumbnails()))); }
/// <summary> /// 获取附件存储的相对路径 /// </summary> public virtual string GetRelativePath() { TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(this.TenantTypeId); if (tenantAttachmentSettings == null) { return(string.Empty); } IStoreProvider storeProvider = DIContainer.ResolveNamed <IStoreProvider>(tenantAttachmentSettings.StoreProviderName); if (storeProvider == null) { return(string.Empty); } string[] datePaths = new string[] { tenantAttachmentSettings.TenantAttachmentDirectory }; datePaths = datePaths.Union(this.DateCreated.ToString("yyyy-MM-dd").Split('-')).ToArray(); return(storeProvider.JoinDirectory(datePaths)); }
/// <summary> /// 输出html编辑器产生的内容,根据显示区域的宽度自动调整图片尺寸,并引入js脚本 /// </summary> /// <param name="htmlHelper"></param> /// <param name="tenantTypeId">租户类型id</param> /// <param name="content">html编辑器的内容</param> /// <param name="imageWidth">显示区域的图片宽度</param> /// <returns></returns> public static MvcHtmlString DisplayHtmlEditorContent(this HtmlHelper htmlHelper, string tenantTypeId, string content, int imageWidth) { if (string.IsNullOrEmpty(content)) { return(MvcHtmlString.Create(string.Empty)); } htmlHelper.Style("~/Bundle/Styles/CodeHighlighter"); htmlHelper.Script("~/Bundle/Scripts/CodeHighlighter"); htmlHelper.Style("~/Bundle/Styles/FancyBox"); htmlHelper.Script("~/Bundle/Scripts/FancyBox"); htmlHelper.Script("~/Scripts/tunynet/body.js"); htmlHelper.Script("~/Scripts/tunynet/insertMedia.js"); TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); content = content.Replace("width=\"" + tenantAttachmentSettings.InlinedImageWidth + "\"", "width=\"" + imageWidth + "\""); return(MvcHtmlString.Create(content)); }
/// <summary> /// 获取照片的EXIF数据 /// </summary> /// <param name="photoId">照片id</param> /// <returns>返回照片的EXIF数据</returns> public Dictionary <int, string> GetPhotoEXIFMetaData(long photoId) { Dictionary <int, string> EXIFMetaData = new Dictionary <int, string>(); Photo photo = this.GetPhoto(photoId); if (photo == null || string.IsNullOrEmpty(photo.RelativePath) || (!photo.RelativePath.ToLower().EndsWith(".jpg") && !photo.RelativePath.ToLower().EndsWith(".jpeg"))) { return(EXIFMetaData); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Photo()); IStoreProvider storeProvider = DIContainer.ResolveNamed <IStoreProvider>(tenantAttachmentSettings.StoreProviderName); IStoreFile file = storeProvider.GetFile(photo.RelativePath, ""); if (file != null) { using (Stream stream = file.OpenReadStream()) { EXIFMetaData = new EXIFMetaDataService().Read(stream); } } return(EXIFMetaData); }
/// <summary> /// 上传照片(页面) /// </summary> public ActionResult Upload(string spaceKey, long albumId = 0) { IUser owner = userService.GetUser(spaceKey); if (owner == null) { return(HttpNotFound()); } var user = UserContext.CurrentUser; if (user == null) { return(Redirect(SiteUrls.Instance().Login(true))); } string errorMessage = string.Empty; if (!authorizer.Photo_Upload(spaceKey, out errorMessage)) { return(Redirect(SiteUrls.Instance().SystemMessage(TempData, new SystemMessageViewModel { Body = errorMessage, Title = "没有权限", StatusMessageType = StatusMessageType.Hint }))); } TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(TenantTypeIds.Instance().Photo()); //提示可上传的图片大小、类型 ViewData["attachmentLength"] = tenantAttachmentSettings.MaxAttachmentLength; ViewData["allowedFileExtensions"] = tenantAttachmentSettings.AllowedFileExtensions; //相册下拉框 GetAlbumList(albumId); pageResourceManager.InsertTitlePart("上传照片"); return(View()); }
/// <summary> /// 升级照片附件 /// </summary> /// <returns></returns> private bool UpdatePhotoBySQL(out string message) { SqlConnection sqlConnection = GetConnection(); List <long> photoIds = new List <long>(); List <long> albumIds = new List <long>(); Dictionary <long, List <long> > photosInAlbum = new Dictionary <long, List <long> >(); Directory.SetCurrentDirectory(currentDirectory); int allCount = 0; int moveCount = 0; bool result = false; StringBuilder messageBuilder = new StringBuilder(); try { sqlConnection.Open(); SqlCommand selectCommand = new SqlCommand("select PhotoId,AlbumId from spb_Photos", sqlConnection); SqlDataReader dr = selectCommand.ExecuteReader(CommandBehavior.CloseConnection); while (dr.Read()) { photoIds.Add(dr.GetInt64(0)); albumIds.Add(dr.GetInt64(1)); if (!photosInAlbum.ContainsKey(dr.GetInt64(1))) { photosInAlbum[dr.GetInt64(1)] = new List <long>(); } photosInAlbum[dr.GetInt64(1)].Add(dr.GetInt64(0)); } dr.Close(); sqlConnection.Close(); foreach (var albumId in albumIds) { string newPhotoRelatedPath = GetRelativePathById(albumId, "Photo"); if (!Directory.Exists(newPhotoRelatedPath)) { Directory.CreateDirectory(newPhotoRelatedPath); } foreach (var photoId in photosInAlbum[albumId]) { string oldPhotoRelatedPath = Path.Combine(currentDirectory, GetOldRelativePath("Galleries", photoId)); if (!Directory.Exists(oldPhotoRelatedPath)) { continue; } foreach (var photoFilePath in Directory.GetFiles(oldPhotoRelatedPath)) { allCount++; FileInfo oldFileInfo = new FileInfo(photoFilePath); string newPhotoFilePath = Path.Combine(currentDirectory, newPhotoRelatedPath, oldFileInfo.Name); if (!System.IO.File.Exists(newPhotoFilePath)) { System.IO.File.Move(photoFilePath, newPhotoFilePath); moveCount++; string tenantTypeId = "100302"; TenantAttachmentSettings tenantAttachmentSettings = TenantAttachmentSettings.GetRegisteredSettings(tenantTypeId); if (tenantAttachmentSettings != null && tenantAttachmentSettings.ImageSizeTypes != null && tenantAttachmentSettings.ImageSizeTypes.Count > 0) { foreach (var imageSizeType in tenantAttachmentSettings.ImageSizeTypes) { IStoreFile file = storeProvider.GetResizedImage(newPhotoRelatedPath, oldFileInfo.Name, imageSizeType.Size, imageSizeType.ResizeMethod); } } } break; } } } } catch (Exception e) { sqlConnection.Close(); } messageBuilder.AppendFormat("{0}:一共找到{1}个可以升级的照片", storeProvider.JoinDirectory("Old", "Galleries"), allCount); if (moveCount > 0) { result = true; messageBuilder.AppendFormat(",成功升级了{0}个照片", moveCount); } message = messageBuilder.ToString(); return(result); }