CKEditor hiện nay là trình soạn thảo văn bản thông dụng và phổ biến nhất thế giới. Tuy nhiên, việc cái đặt CKEditor thì rất dễ dàng, nhưng mặc định, trình soạn thảo này chỉ hỗ trợ soạn thảo mà chưa có sẵn chức năng upload hình ảnh, file lên server.
Trong bài viết này, mình sẽ hướng dẫn các bạn viết 1 Adapter để upload ảnh lên server
Cài đặt CKEditor
Thêm đoạn code sau vào HomeController:public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
private readonly IWebHostEnvironment _webHostEnvironment;
public HomeController(ILogger<HomeController> logger, IWebHostEnvironment webHostEnvironment)
{
_logger = logger;
_webHostEnvironment = webHostEnvironment;
}
public IActionResult CkEditor()
{
//example data
var model = new PostModel
{
Content = "<p>Click on the Image Below to resize</p>"
};
return View(model);
}
[HttpPost]
public IActionResult UploadFile(IFormFile file)
{
var dir = Path.Combine(_webHostEnvironment.ContentRootPath, "wwwroot");
using (var fileStream = new FileStream(Path.Combine(dir, "FileUploads", file.FileName), FileMode.Create))
{
file.CopyTo(fileStream);
}
return Json(new
{
data = "/FileUploads/" + file.FileName
});
}
[HttpPost]
public IActionResult SaveData(PostModel model)
{
return View(model);
}
}
Tạo 1 view mới cho action CkEditor. Khai báo lib CkEditor
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script class="html">
Khởi tạo CkEditor từ model có sẵn:
@model TinyMceExample.Models.PostModel;
<h1>Hello World</h1>
<form id="form" asp-controller="Home" asp-action="SaveData" onsubmit="handleSubmit()">
<input type="hidden" id="jdr" asp-for="@Model.Content" />
<div id="editor">
@Html.Raw(Model.Content)
</div>
<input type="submit" value="Save data" />
</form>
@section scripts{
<script src="https://cdn.ckeditor.com/ckeditor5/35.4.0/classic/ckeditor.js"></script>
<script>
ClassicEditor
.create( document.querySelector( '#editor' ))
.catch( error => {
console.error( error );
} );
</script>
}
Custom Upload Adapter
Tạo 1 plugin mới 'FileRepository', gồm 3 hàm:- _initRequest()
- _initListeners()
- _sendRequest()
class MyUploadAdapter {
constructor(loader) {
// The file loader instance to use during the upload.
this.loader = loader;
}
// Starts the upload process.
upload() {
return this.loader.file
.then(file => new Promise((resolve, reject) => {
this._initRequest();
this._initListeners(resolve, reject, file);
this._sendRequest(file);
}));
}
// Aborts the upload process.
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
// Initializes the XMLHttpRequest object using the URL passed to the constructor.
_initRequest() {
const xhr = this.xhr = new XMLHttpRequest();
// Note that your request may look different. It is up to you and your editor
// integration to choose the right communication channel. This example uses
// a POST request with JSON as a data structure but your configuration
// could be different.
xhr.open('POST', '/Home/UploadFile', true);
xhr.responseType = 'json';
}
// Initializes XMLHttpRequest listeners.
_initListeners(resolve, reject, file) {
const xhr = this.xhr;
const loader = this.loader;
const genericErrorText = `Couldn't upload file: ${file.name}.`;
xhr.addEventListener('error', () => reject(genericErrorText));
xhr.addEventListener('abort', () => reject());
xhr.addEventListener('load', () => {
const response = xhr.response;
// This example assumes the XHR server's "response" object will come with
// an "error" which has its own "message" that can be passed to reject()
// in the upload promise.
//
// Your integration may handle upload errors in a different way so make sure
// it is done properly. The reject() function must be called when the upload fails.
if (!response || response.error) {
return reject(response && response.error ? response.error.message : genericErrorText);
}
// If the upload is successful, resolve the upload promise with an object containing
// at least the "default" URL, pointing to the image on the server.
// This URL will be used to display the image in the content. Learn more in the
// UploadAdapter#upload documentation.
resolve({
default: response.url
});
});
// Upload progress when it is supported. The file loader has the #uploadTotal and #uploaded
// properties which are used e.g. to display the upload progress bar in the editor
// user interface.
if (xhr.upload) {
xhr.upload.addEventListener('progress', evt => {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
// Prepares the data and sends the request.
_sendRequest(file) {
// Prepare the form data.
const data = new FormData();
data.append('file', file);
// Important note: This is the right place to implement security mechanisms
// like authentication and CSRF protection. For instance, you can use
// XMLHttpRequest.setRequestHeader() to set the request headers containing
// the CSRF token generated earlier by your application.
// Send the request.
this.xhr.send(data);
}
}
// ...
function MyCustomUploadAdapterPlugin(editor) {
editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
// Configure the URL to the upload script in your back-end here!
return new MyUploadAdapter(loader);
};
}
Thêm plugin vào ClassicEditor
ClassicEditor
.create( document.querySelector( '#editor' ), {
extraPlugins: [MyCustomUploadAdapterPlugin]
} )
.catch( error => {
console.error( error );
} );
Chúc các bạn thành công
Nhatkyhoctap's blog
Nhận xét
Đăng nhận xét