Как вставить Image
с местной машины в Kendo Editor
? Я не могу выполнить это действие.Kendo-editor: Как вставить изображение в редактор кендо?
ответ
Вы должны использовать image-Browser
в Kendo-Editor
, по умолчанию Kendo-Editor
магазин звену вставки изображения, в вашем случае, если вы загрузите изображение с локального компьютера. Вы должны создать пользовательский контроллер для загрузки изображения на сервер и возврата ссылки на изображение.
Я упоминал ниже код, я надеюсь, что этот код полезен для вас.
Создать контроллер с именем ImageBrowser
public class ImageBrowserController : Controller
{
private const string contentFolderRoot = "~/";
private const string prettyName = "ServerPathForImage/";
private const string DefaultFilter = "*.png,*.gif,*.jpg,*.jpeg";
private const int ThumbnailHeight = 80;
private const int ThumbnailWidth = 80;
private readonly DirectoryBrowser directoryBrowser;
private readonly ThumbnailCreator thumbnailCreator;
public ImageBrowserController()
{
directoryBrowser = new DirectoryBrowser();
thumbnailCreator = new ThumbnailCreator();
}
public string ContentPath
{
get
{
return Path.Combine(contentFolderRoot, prettyName);
}
}
private string ToAbsolute(string virtualPath)
{
return VirtualPathUtility.ToAbsolute(virtualPath);
}
private string CombinePaths(string basePath, string relativePath)
{
return VirtualPathUtility.Combine(VirtualPathUtility.AppendTrailingSlash(basePath), relativePath);
}
public virtual bool AuthorizeRead(string path)
{
return CanAccess(path);
}
protected virtual bool CanAccess(string path)
{
return path.StartsWith(ToAbsolute(ContentPath), StringComparison.OrdinalIgnoreCase);
}
private string NormalizePath(string path)
{
if (string.IsNullOrEmpty(path))
{
return ToAbsolute(ContentPath);
}
return CombinePaths(ToAbsolute(ContentPath), path);
}
public virtual JsonResult Read(string path)
{
path = NormalizePath(path);
if (AuthorizeRead(path))
{
try
{
directoryBrowser.Server = Server;
var result = directoryBrowser
.GetContent(path, DefaultFilter)
.Select(f => new
{
name = f.Name,
type = f.Type == EntryType.File ? "f" : "d",
size = f.Size
});
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (DirectoryNotFoundException)
{
throw new HttpException(404, "File Not Found");
}
}
throw new HttpException(403, "Forbidden");
}
public virtual bool AuthorizeThumbnail(string path)
{
return CanAccess(path);
}
[OutputCache(Duration = 3600, VaryByParam = "path")]
public virtual ActionResult Thumbnail(string path)
{
path = NormalizePath(path);
if (AuthorizeThumbnail(path))
{
var physicalPath = Server.MapPath(path);
if (System.IO.File.Exists(physicalPath))
{
Response.AddFileDependency(physicalPath);
return CreateThumbnail(physicalPath);
}
else
{
throw new HttpException(404, "File Not Found");
}
}
else
{
throw new HttpException(403, "Forbidden");
}
}
private FileContentResult CreateThumbnail(string physicalPath)
{
using (var fileStream = System.IO.File.OpenRead(physicalPath))
{
var desiredSize = new ImageSize
{
Width = ThumbnailWidth,
Height = ThumbnailHeight
};
const string contentType = "image/png";
return File(thumbnailCreator.Create(fileStream, desiredSize, contentType), contentType);
}
}
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Destroy(string path, string name, string type)
{
path = NormalizePath(path);
if (!string.IsNullOrEmpty(name) && !string.IsNullOrEmpty(type))
{
path = CombinePaths(path, name);
if (type.ToLowerInvariant() == "f")
{
DeleteFile(path);
}
else
{
DeleteDirectory(path);
}
return Json(null);
}
throw new HttpException(404, "File Not Found");
}
public virtual bool AuthorizeDeleteFile(string path)
{
return CanAccess(path);
}
public virtual bool AuthorizeDeleteDirectory(string path)
{
return CanAccess(path);
}
protected virtual void DeleteFile(string path)
{
if (!AuthorizeDeleteFile(path))
{
throw new HttpException(403, "Forbidden");
}
var physicalPath = Server.MapPath(path);
if (System.IO.File.Exists(physicalPath))
{
System.IO.File.Delete(physicalPath);
}
}
protected virtual void DeleteDirectory(string path)
{
if (!AuthorizeDeleteDirectory(path))
{
throw new HttpException(403, "Forbidden");
}
var physicalPath = Server.MapPath(path);
if (Directory.Exists(physicalPath))
{
Directory.Delete(physicalPath, true);
}
}
public virtual bool AuthorizeCreateDirectory(string path, string name)
{
return CanAccess(path);
}
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Create(string path, FileBrowserEntry entry)
{
path = NormalizePath(path);
var name = entry.Name;
if (!string.IsNullOrEmpty(name) && AuthorizeCreateDirectory(path, name))
{
var physicalPath = Path.Combine(Server.MapPath(path), name);
if (!Directory.Exists(physicalPath))
{
Directory.CreateDirectory(physicalPath);
}
return Json(null);
}
throw new HttpException(403, "Forbidden");
}
public virtual bool AuthorizeUpload(string path, HttpPostedFileBase file)
{
return CanAccess(path) && IsValidFile(file.FileName);
}
private bool IsValidFile(string fileName)
{
var extension = Path.GetExtension(fileName);
var allowedExtensions = DefaultFilter.Split(',');
return allowedExtensions.Any(e => e.EndsWith(extension, StringComparison.InvariantCultureIgnoreCase));
}
[AcceptVerbs(HttpVerbs.Post)]
public virtual ActionResult Upload(string path, HttpPostedFileBase file)
{
path = NormalizePath(path);
var fileName = Path.GetFileName(file.FileName);
if (AuthorizeUpload(path, file))
{
file.SaveAs(Path.Combine(Server.MapPath(path), fileName));
return Json(new
{
size = file.ContentLength,
name = fileName,
type = "f"
}, "text/plain");
}
throw new HttpException(403, "Forbidden");
}
[OutputCache(Duration = 360, VaryByParam = "path")]
public ActionResult Image(string path)
{
path = NormalizePath(path);
if (AuthorizeImage(path))
{
var physicalPath = Server.MapPath(path);
if (System.IO.File.Exists(physicalPath))
{
const string contentType = "image/png";
return File(System.IO.File.OpenRead(physicalPath), contentType);
}
}
throw new HttpException(403, "Forbidden");
}
public virtual bool AuthorizeImage(string path)
{
return CanAccess(path) && IsValidFile(Path.GetExtension(path));
}
}
В view
вам нужно создать text-area
<textarea class="classicEditor" name="Contents" id="classicEditor"></textarea>
Теперь вам нужно связать kendo-editor
с text-area
в javascript
<script type="text/javascript">
$(document).ready(function() {
$("#classicEditor").kendoEditor({
imageBrowser: {
transport: {
read: "@Url.Action("Read", "ImageBrowser")",
destroy: {
url: "@Url.Action("Destroy", "ImageBrowser")",
type: "POST"
},
create: {
url: "@Url.Action("Create", "ImageBrowser")",
type: "POST"
},
thumbnailUrl: "@Url.Action("Thumbnail", "ImageBrowser")",
uploadUrl: "@Url.Action("Upload", "ImageBrowser")",
imageUrl: "/ImageBrowser/Image?path={0}"
}
},
tools: [
"bold",
"italic",
"underline",
"strikethrough",
"justifyLeft",
"justifyCenter",
"justifyRight",
"justifyFull",
"VerticalAlignTop",
"Vertical-AlignTop",
"Verticaltop",
"insertUnorderedList",
"insertOrderedList",
"indent",
"outdent",
"insertImage",
"subscript",
"superscript",
"createTable",
"addRowAbove",
"addRowBelow",
"addColumnLeft",
"addColumnRight",
"deleteRow",
"deleteColumn",
"viewHtml",
"formatting",
"cleanFormatting",
"fontName",
"fontSize",
"foreColor",
"backColor",
"print"
]
});
})
</script>
Если у вас возникли проблемы с размещением image-browser
, вам необходимо решить с помощью приведенного ниже кода.
<style>
.k-window {
width: 430px !important;
}
.k-imagebrowser {
margin-left: 25px !important;
}
</style>
Вы должны использовать браузер файлов и изображений, которые позволяют загружать изображения на ваш сервер, а затем использовать их. Как descrbied здесь: http://demos.telerik.com/kendo-ui/editor/imagebrowser
Благодарим за то, что вы указали меня в нужном направлении. – Tasawar
- 1. Создание Кендо Редактор READONLY
- 2. selectionStart в textarea, предоставленный kendoeditor
- 3. Вставить изображение в редактор Primefaces
- 4. Вставить изображение в редактор tinymce
- 5. Как вставить изображение в редактор magento cms
- 6. Как вставить кендо-окно в кендо-дерево?
- 7. Невозможно вставить изображение через Umbraco RichText редактор
- 8. KendoEditor Установить фокус в конце текста
- 9. Как вставить изображение с клиентской стороны в редактор?
- 10. Кендо - вставить атрибут события
- 11. Скопировать вставить изображение в редактор Wordpress + импорт в медиа-библиотеку?
- 12. Как вставить изображение в tinymce?
- 13. Dropdown редактор списка в Aurelia Кендо Сетка
- 14. kendoEditor не появляется
- 15. Пустой Кендо-редактор с углового контроллера
- 16. Кендо Сетка Сортировки Сломанный с редактор пользовательского
- 17. Trigger OnChange событие Кендо Редактор виджета
- 18. Kendo UI (Редактор) - Вкл. Ссылку, Вставить HTML-код
- 19. Как сделать изображение в сетке гиперссылки кендо
- 20. Как вставить редактор HTML в сетку?
- 21. Как вставить текст в редактор Cloud9?
- 22. Cygwin: Как вставить текст в редактор vi
- 23. Запрошенный URL вернулся 403 в KendoEditor
- 24. Кендо Сетка PopUp редактор не закрывается
- 25. Html Кендо редактор не отображает верхнюю панель
- 26. Изменить кендо UI редактор при нажатии клавиш
- 27. Где вставить wirisplugins.js в редактор joomla tinymce
- 28. Отображение значков для типов файлов в KendoEditor FileBrowser
- 29. Как удалить из скроллбар кендо редактор текстовой области
- 30. Любые идеи о том, как встроить изображение в текстовый редактор?
Спасибо, что это было полезно. Это почти решило мою проблему. – Tasawar