public ActionResult Upload(int id, string content, int width, int height) { var media = Services.ContentManager.Get(id).As <MediaPart>(); if (media == null) { return(HttpNotFound()); } const string signature = "data:image/jpeg;base64,"; if (!content.StartsWith(signature, StringComparison.OrdinalIgnoreCase)) { return(HttpNotFound()); } var image = media.As <ImagePart>(); content = content.Substring(signature.Length); var buffer = Convert.FromBase64String(content); _mediaLibraryService.DeleteFile(media.FolderPath, media.FileName); using (var stream = new MemoryStream(buffer)) { _mediaLibraryService.UploadMediaFile(media.FolderPath, media.FileName, stream); } image.Width = width; image.Height = height; media.MimeType = "image/png"; return(Json(true)); }
protected void RemoveMedia(MediaPart part) { if (!string.IsNullOrEmpty(part.FileName)) { _mediaLibraryService.DeleteFile(part.FolderPath, part.FileName); } }
private void DeleteImage(string imageGalleryName, string imageName, ImageGalleryImageSettingsRecord imageSettings) { if (imageSettings != null) { _imageRepository.Delete(imageSettings); } _mediaService.DeleteFile(GetMediaPath(imageGalleryName), imageName); _thumbnailService.DeleteThumbnail(_storageProvider.Combine(GetMediaPath(imageGalleryName), imageName)); }
public ActionResult Upload(int id, string content, int width, int height) { if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia)) { return(new HttpUnauthorizedResult()); } var media = Services.ContentManager.Get(id).As <MediaPart>(); if (media == null) { return(HttpNotFound()); } // Check permission. var rootMediaFolder = _mediaLibraryService.GetRootMediaFolder(); if (!Services.Authorizer.Authorize(Permissions.ImportMediaContent) && !_mediaLibraryService.CanManageMediaFolder(media.FolderPath)) { return(new HttpUnauthorizedResult()); } const string signature = "data:image/jpeg;base64,"; if (!content.StartsWith(signature, StringComparison.OrdinalIgnoreCase)) { return(HttpNotFound()); } var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>(); // skip file if the allowed extensions is defined and doesn't match if (!settings.IsFileAllowed(Path.GetFileName(media.FileName))) { return(Json(false)); } var image = media.As <ImagePart>(); content = content.Substring(signature.Length); var buffer = Convert.FromBase64String(content); _mediaLibraryService.DeleteFile(media.FolderPath, media.FileName); using (var stream = new MemoryStream(buffer)) { _mediaLibraryService.UploadMediaFile(media.FolderPath, media.FileName, stream); } image.Width = width; image.Height = height; media.MimeType = "image/png"; return(Json(true)); }
private XRpcStruct MetaWeblogNewMediaObject( string userName, string password, XRpcStruct file, UrlHelper url) { List <LocalizedString> validationErrors; var user = _membershipService.ValidateUser(userName, password, out validationErrors); if (!_authorizationService.TryCheckAccess(Permissions.ManageOwnMedia, user, null) && !_authorizationService.TryCheckAccess(Permissions.EditMediaContent, user, null)) { throw new OrchardCoreException(T("Access denied")); } var name = file.Optional <string>("name"); var bits = file.Optional <byte[]>("bits"); string directoryName = Path.GetDirectoryName(name); if (string.IsNullOrWhiteSpace(directoryName)) // Some clients only pass in a name path that does not contain a directory component. { directoryName = "media"; } // If the user only has access to his own folder, rewrite the folder name if (!_authorizationService.TryCheckAccess(Permissions.EditMediaContent, user, null)) { directoryName = Path.Combine(_mediaLibraryService.GetRootedFolderPath(directoryName)); } try { // delete the file if it already exists, e.g. an updated image in a blog post // it's safe to delete the file as each content item gets a specific folder _mediaLibraryService.DeleteFile(directoryName, Path.GetFileName(name)); } catch { // current way to delete a file if it exists } string publicUrl = _mediaLibraryService.UploadMediaFile(directoryName, Path.GetFileName(name), bits); var mediaPart = _mediaLibraryService.ImportMedia(directoryName, Path.GetFileName(name)); try { _contentManager.Create(mediaPart); } catch { } return(new XRpcStruct() // Some clients require all optional attributes to be declared Wordpress responds in this way as well. .Set("file", publicUrl) .Set("url", url.MakeAbsolute(publicUrl)) .Set("type", file.Optional <string>("type"))); }
protected void RemoveMedia(MediaPart part) { if (!string.IsNullOrEmpty(part.FileName)) { var mediaItemsUsingTheFile = _contentManager.Query <MediaPart, MediaPartRecord>() .ForVersion(VersionOptions.Latest) .Where(x => x.FolderPath == part.FolderPath && x.FileName == part.FileName) .Count(); if (mediaItemsUsingTheFile == 1) // if the file is referenced only by the deleted media content, the file too can be removed. { _mediaLibraryService.DeleteFile(part.FolderPath, part.FileName); } } }
public ActionResult Replace(int replaceId, string type, string url) { if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia)) { return(new HttpUnauthorizedResult()); } var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId); if (replaceMedia == null) { return(HttpNotFound()); } // Check permission if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath)) { return(new HttpUnauthorizedResult()); } var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>(); var allowedExtensions = (settings.UploadAllowedFileTypeWhitelist ?? "") .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Where(x => x.StartsWith(".")); try { var filename = Path.GetFileName(url); // skip file if the allowed extensions is defined and doesn't match if (allowedExtensions.Any()) { if (!allowedExtensions.Any(e => filename.EndsWith(e, StringComparison.OrdinalIgnoreCase))) { throw new Exception(T("This file type is not allowed: {0}", Path.GetExtension(filename)).Text); } } var buffer = new WebClient().DownloadData(url); var stream = new MemoryStream(buffer); var mimeType = _mimeTypeProvider.GetMimeType(filename); string replaceContentType = _mediaLibraryService.MimeTypeToContentType(stream, mimeType, type) ?? type; if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase)) { throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text); } _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName); _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, stream); replaceMedia.MimeType = mimeType; // Force a publish event which will update relevant Media properties replaceMedia.ContentItem.VersionRecord.Published = false; Services.ContentManager.Publish(replaceMedia.ContentItem); return(new JsonResult { Data = new { replaceMedia.FolderPath, MediaPath = replaceMedia.FileName } }); } catch (Exception e) { return(new JsonResult { Data = new { Success = false, error = e.Message } }); } }
public ActionResult Replace(int replaceId, string type) { if (!Services.Authorizer.Authorize(om.Permissions.ManageOwnMedia)) { return(new HttpUnauthorizedResult()); } var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId); if (replaceMedia == null) { return(HttpNotFound()); } // Check permission if (!(_mediaLibraryService.CheckMediaFolderPermission(om.Permissions.EditMediaContent, replaceMedia.FolderPath) && _mediaLibraryService.CheckMediaFolderPermission(om.Permissions.ImportMediaContent, replaceMedia.FolderPath)) && !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath)) { return(new HttpUnauthorizedResult()); } var statuses = new List <object>(); var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>(); // Loop through each file in the request for (int i = 0; i < HttpContext.Request.Files.Count; i++) { // Pointer to file var file = HttpContext.Request.Files[i]; var filename = Path.GetFileName(file.FileName); // if the file has been pasted, provide a default name if (file.ContentType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) && !filename.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) { filename = "clipboard.png"; } // skip file if the allowed extensions is defined and doesn't match if (!settings.IsFileAllowed(filename)) { statuses.Add(new { error = T("This file is not allowed: {0}", filename).Text, progress = 1.0, }); continue; } try { var mimeType = _mimeTypeProvider.GetMimeType(filename); string replaceContentType = _mediaLibraryService.MimeTypeToContentType(file.InputStream, mimeType, type) ?? type; if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase)) { throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text); } var mediaItemsUsingTheFile = Services.ContentManager.Query <MediaPart, MediaPartRecord>() .ForVersion(VersionOptions.Latest) .Where(x => x.FolderPath == replaceMedia.FolderPath && x.FileName == replaceMedia.FileName) .Count(); if (mediaItemsUsingTheFile == 1) { // if the file is referenced only by the deleted media content, the file too can be removed. _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName); } else { // it changes the media file name replaceMedia.FileName = filename; } _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, file.InputStream); replaceMedia.MimeType = mimeType; // Force a publish event which will update relevant Media properties replaceMedia.ContentItem.VersionRecord.Published = false; Services.ContentManager.Publish(replaceMedia.ContentItem); statuses.Add(new { id = replaceMedia.Id, name = replaceMedia.Title, type = replaceMedia.MimeType, size = file.ContentLength, progress = 1.0, url = replaceMedia.FileName, }); } catch (Exception ex) { Logger.Error(ex, "Unexpected exception when uploading a media."); statuses.Add(new { error = T(ex.Message).Text, progress = 1.0, }); } } return(Json(statuses, JsonRequestBehavior.AllowGet)); }
public override void Validated(FormValidatedEventContext context) { if (!context.ModelState.IsValid) { //Clean up on validation fail foreach (var element in context.Form.Elements.Flatten()) { if (element is FileField) { var fileFieldElement = element as FileField; if (fileFieldElement == null) { continue; } var postedFileValue = context.ValueProvider.GetValue(fileFieldElement.Name); if (postedFileValue == null) { continue; } var postedFiles = (HttpPostedFileBase[])postedFileValue.RawValue; if (postedFiles == null && postedFiles.Length != 1) { continue; } var filePath = context.Values[fileFieldElement.Name]; if (string.IsNullOrWhiteSpace(filePath)) { continue; } _mediaLibraryService.DeleteFile( Path.GetDirectoryName(filePath), Path.GetFileName(filePath)); } } } else { foreach (var element in context.Form.Elements.Flatten()) { var fileFieldElement = element as FileField; if (fileFieldElement == null) { continue; } var postedFileValue = context.ValueProvider.GetValue(fileFieldElement.Name); if (postedFileValue == null) { continue; } var postedFiles = (HttpPostedFileBase[])postedFileValue.RawValue; if (postedFiles == null && postedFiles.Length != 1) { continue; } var filePath = context.Values[fileFieldElement.Name]; if (string.IsNullOrWhiteSpace(filePath)) { continue; } var mediaPart = _mediaLibraryService.ImportMedia( Path.GetDirectoryName(filePath), Path.GetFileName(filePath)); _contentManager.Create(mediaPart); } } }
public ActionResult DeleteFile(Guid guid, string name, string returnValue) { var fileRecord = fileRepository.Table.FirstOrDefault(c => c.FolderGuid == guid); ContentItem item = null; if (fileRecord != null) { item = _services.ContentManager.Get(fileRecord.ContentItemRecord.Id); if (item != null) { if (!item.Has <FileUploadPart>()) { return(HttpNotFound()); } if (!this.contentOwnershipService.CurrentUserCanEditContent(item)) { throw new UnauthorizedAccessException(); } } } var folders = _mediaService.GetMediaFolders("Uploads"); var folder = folders.SingleOrDefault(x => x.Name == guid.ToString()); if (folder == null) { return(HttpNotFound()); } if (this.storageProvider.FileExists(this.storageProvider.Combine(folder.MediaPath, name))) { _mediaService.DeleteFile(folder.MediaPath, name); } fileRecord.FilesCount = _mediaService.GetMediaFiles(folder.MediaPath).Count(); if (item != null) { int userId = _services.WorkContext.CurrentUser.Id; string description = string.Format(CultureInfo.CurrentUICulture, "Delete the file '{0}' from '{1}'", name, this.GetContentItemDescriptionForActivityStream(item)); RouteValueDictionary routeValueDictionary = new RouteValueDictionary(); routeValueDictionary.Add("action", "Display"); routeValueDictionary.Add("controller", "Item"); routeValueDictionary.Add("area", "Orchard.CRM.Core"); routeValueDictionary.Add("id", fileRecord.ContentItemRecord.Id); this.activityStreamService.WriteChangesToStreamActivity(userId, item.Id, item.VersionRecord.Id, new ActivityStreamChangeItem[] { }, description, routeValueDictionary); } if (Request.IsAjaxRequest()) { return(this.Json(new { IsDone = true }, JsonRequestBehavior.AllowGet)); } else if (!string.IsNullOrEmpty(returnValue)) { return(Redirect(returnValue)); } else if (fileRecord != null) { return(this.RedirectToAction("Display", "Ticket", new { area = "Orchard.CRM.Core", id = fileRecord.ContentItemRecord.Id })); } else { return(this.RedirectToAction("Search", "Ticket", new { area = "Orchard.CRM.Core" })); } }
public ActionResult Replace(int replaceId, string type) { if (!Services.Authorizer.Authorize(Permissions.ManageOwnMedia)) { return(new HttpUnauthorizedResult()); } var replaceMedia = Services.ContentManager.Get <MediaPart>(replaceId); if (replaceMedia == null) { return(HttpNotFound()); } // Check permission if (!Services.Authorizer.Authorize(Permissions.ManageMediaContent) && !_mediaLibraryService.CanManageMediaFolder(replaceMedia.FolderPath)) { return(new HttpUnauthorizedResult()); } var statuses = new List <object>(); var settings = Services.WorkContext.CurrentSite.As <MediaLibrarySettingsPart>(); var allowedExtensions = (settings.UploadAllowedFileTypeWhitelist ?? "") .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Where(x => x.StartsWith(".")); // Loop through each file in the request for (int i = 0; i < HttpContext.Request.Files.Count; i++) { // Pointer to file var file = HttpContext.Request.Files[i]; var filename = Path.GetFileName(file.FileName); // if the file has been pasted, provide a default name if (file.ContentType.Equals("image/png", StringComparison.InvariantCultureIgnoreCase) && !filename.EndsWith(".png", StringComparison.InvariantCultureIgnoreCase)) { filename = "clipboard.png"; } // skip file if the allowed extensions is defined and doesn't match if (allowedExtensions.Any()) { if (!allowedExtensions.Any(e => filename.EndsWith(e, StringComparison.OrdinalIgnoreCase))) { statuses.Add(new { error = T("This file type is not allowed: {0}", Path.GetExtension(filename)).Text, progress = 1.0, }); continue; } } try { var mimeType = _mimeTypeProvider.GetMimeType(filename); string replaceContentType = _mediaLibraryService.MimeTypeToContentType(file.InputStream, mimeType, type) ?? type; if (!replaceContentType.Equals(replaceMedia.TypeDefinition.Name, StringComparison.OrdinalIgnoreCase)) { throw new Exception(T("Cannot replace {0} with {1}", replaceMedia.TypeDefinition.Name, replaceContentType).Text); } _mediaLibraryService.DeleteFile(replaceMedia.FolderPath, replaceMedia.FileName); _mediaLibraryService.UploadMediaFile(replaceMedia.FolderPath, replaceMedia.FileName, file.InputStream); replaceMedia.MimeType = mimeType; // Force a publish event which will update relevant Media properties replaceMedia.ContentItem.VersionRecord.Published = false; Services.ContentManager.Publish(replaceMedia.ContentItem); statuses.Add(new { id = replaceMedia.Id, name = replaceMedia.Title, type = replaceMedia.MimeType, size = file.ContentLength, progress = 1.0, url = replaceMedia.FileName, }); } catch (Exception ex) { Logger.Error(ex, "Unexpected exception when uploading a media."); statuses.Add(new { error = T(ex.Message).Text, progress = 1.0, }); } } return(Json(statuses, JsonRequestBehavior.AllowGet)); }