Reputation: 166
I installed CKEDITOR 5 for my ASP.Net Core based blog to upload blogs with images and some html styles. But I want to upload files in my IIS static files some directory like "wwwroot/bloguploads/" is it possible ?
Which parameters should I change on creating the editor to change upload action?
Upvotes: 2
Views: 2148
Reputation: 615
This is my project cshtml file
<div class="tab-panels">
<!-- The toolbar will be rendered in this container. -->
<div id="toolbar-container"></div>
<!-- This container will become the editable. -->
<div id="desEditor"></div>
@Html.HiddenFor(model => model.Description);
</div><!-- .tab-panels -->
javascript
class MyUploadAdapter {
constructor(loader) {
// The file loader instance to use during the upload.
this.loader = loader;
this.url = '/VehicleKey/DocUploadImage';
}
// 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();
}
}
_initRequest() {
const xhr = this.xhr = new XMLHttpRequest();
xhr.open('POST', this.url, 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('upload', 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) => {
return new MyUploadAdapter(loader);
};
}
DecoupledEditor.create(document.querySelector('#desEditor'), {
extraPlugins: [MyCustomUploadAdapterPlugin]
})
.then(editor => {
const toolbarContainer = document.querySelector('#toolbar-container');
toolbarContainer.appendChild(editor.ui.view.toolbar.element);
})
.catch(error => {
console.error(error);
});
document.getElementById("btnSubmitKey").addEventListener("click", (e) => {
const richText = document.getElementById('desEditor').innerHTML;
document.getElementById('Description').value = richText;
});
Controller.cs
public async Task<JsonResult> DocUploadImage()
{
try
{
var uploads = Path.Combine(_hostingEnvironment.WebRootPath, "images/vehicle-key");
var filePath = Path.Combine(uploads, "rich-text");
var urls = new List<string>();
//If folder of new key is not exist, create the folder.
if (!Directory.Exists(filePath)) Directory.CreateDirectory(filePath);
foreach (var contentFile in Request.Form.Files)
{
if (contentFile != null && contentFile.Length > 0)
{
await contentFile.CopyToAsync(new FileStream($"{filePath}\\{contentFile.FileName}", FileMode.Create));
urls.Add($"{HttpContext.Request.Host}/rich-text/{contentFile.FileName}");
}
}
return Json(urls);
}
catch (Exception e)
{
return Json(new { error = new { message = e.Message } });
}
}
You can visit CKEditor site to refer more information. There are many examples. You should read carefully.
Upvotes: 4