umbraco - 限制 umbraco 媒体纠察队的上传大小和文件类型
问题描述
尝试像这样通过 dialogService 选择媒体
dialogService.mediaPicker({
startNodeId: undefined,
multiPicker: false,
cropSize: undefined,
showDetails: true,
callback: function (data) {
}
有没有办法自定义这个媒体选择器配置,只允许某些媒体类型并指定大小
解决方案
我认为您最好的选择是为 MediaService 的 Saving 事件创建一个事件处理程序,并在保存文件之前检查您的条件。
更多信息:https ://our.umbraco.com/Documentation/Getting-Started/Code/Subscribing-To-Events/
public class RestrictMediaTypeAndSize : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MediaService.Saving += MediaService_Saving;
}
private void MediaService_Saving(IMediaService sender, Umbraco.Core.Events.SaveEventArgs<Umbraco.Core.Models.IMedia> e)
{
foreach (var media in e.SavedEntities)
{
//you can check for other types of content
if (media.ContentType.Alias == Image.ModelTypeAlias)
{
var fileExtension = GetFileExtension(media);
if (!HasAllowedExtension(fileExtension))
{
//we cancel the saving process
e.Cancel = true;
//we send a message to the user.
var errorMessage = new EventMessage("Error", $"Files of type {fileExtension} are not allowed.");
e.Messages.Add(errorMessage);
//we found an error so we exit the foreach loop to finish the execution.
break;
}
if (!HasValidDimensions(media))
{
//we cancel the saving process
e.Cancel = true;
//we send a message to the user.
var errorMessage = new EventMessage("Error", "Files with a size of (whatever your restrictions) are not allowed.");
e.Messages.Add(errorMessage);
//we found an error so we exit the foreach loop to finish the execution.
break;
}
}
}
}
private bool HasAllowedExtension(string fileExtension)
{
string[] allowedExtensions = new string[] { ".jpg", ".png" };
return allowedExtensions.Contains(fileExtension);
}
private bool HasValidDimensions(IMedia media)
{
//take the image dimensions for the properties populated when you upload the file.
var height = (int)media.Properties["umbracoHeight"].Value;
var width = (int)media.Properties["umbracoWidth"].Value;
//check for whatever conditions you want.
return height < 1000 && width < 2000;
}
private string GetFileExtension(IMedia media)
{
//The umbracoFile Propery is a Json object and we need the src property from it which is the file path.
var filePath = JObject.Parse(media.Properties["umbracoFile"].Value.ToString()).SelectToken("$.src").Value<string>();
return System.IO.Path.GetExtension(filePath);
}
}
推荐阅读
- javascript - Highcharts 列(最小,最大)颜色
- python - 有没有办法用python在意大利语句子中引入标点符号?
- json - 如何通过对没有 STRING_AGG 的不同列进行分组来创建 JSON 列(SQL Server)
- javascript - 创建一个链接以下载文件
- python-3.x - 如何抓取自动完成?
- php - 我不知道为什么我无法连接到我的数据库
- mysql - Mysql - 使用大型相互依赖表(连接表)插入更新的最快方法
- django - Django + React:如何连接它们进行部署?
- java - 当函数 getDisplayString 将在 Hive UDF 中被调用
- c# - 加载具有 1 到 0..1 关系实体框架的实体时出错