skip to Main Content

I have 2 CKEditor fields () in the View.

<div id="editor_1">
     @Html.Raw(@Model.Description_1)
</div>

<div id="editor_2">
     @Html.Raw(@Model.Description_2)
</div>

There is a code that transmits the uploaded image to the controller:

<script>

class MyUploadAdapter {
    
    upload() {
        return this.loader.file
            .then( file => new Promise( ( resolve, reject ) => {
                this._initRequest();
                this._initListeners( resolve, reject, file );
                this._sendRequest( file );
            } ) );
    }

    _initRequest() {
        const xhr = this.xhr = new XMLHttpRequest();
    }
}

</script>

How do I pass in _initRequest() a link to the elements and to understand which field the user is uploading the image to (I need to get the field id)? I tried to figure it out in the controller (in Request class) where I receive the uploaded image, but I couldn’t.

foreach (IFormFile photo in Request.Form.Files)

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    I solved the problem by myself by getting the focus - in which field the image is uploaded. The issue is closed. https://ckeditor.com/docs/ckeditor5/latest/framework/deep-dive/ui/focus-tracking.html


  2. You can create a custom upload adapter to send files to the backend as part of the request. When creating an instance of the adapter, you can get the id of the current element through editor.sourceElement.getAttribute('id').

    Then, create a new XMLHttpRequest and add the element id to the request headerFinally, it is sent to the backend via HTTP request headers.
    On the backend, a method is used to obtain the corresponding id from the request header.
    Here is an example you can use as a reference:

    @model Mymodel
    
    <div class="tab-panels">
    
        <div id="editor_1"></div>
        @Html.Raw(Model?.Description_1)
    
        <div id="editor_2"></div>
        @Html.Raw(Model?.Description_2)
    </div>
    
    
    <script src=https://cdn.ckeditor.com/ckeditor5/41.0.0/classic/ckeditor.js></script>
    
    <script>
    
        class MyUploadAdapter {
            constructor(loader, fieldId) {
                
                this.loader = loader;
                this.url = '/Upload/DocUploadImage';
                this.fieldId = fieldId;
            }
    
            // 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.setRequestHeader('X-FieldId', this.fieldId);
                xhr.responseType = 'json';
               
            }
    
            _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;
    
                    if (!response || response.error) {
                        return reject(response && response.error ? response.error.message : genericErrorText);
                    }
    
                    resolve({
                        default: response.url
                    });
                });
    
                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) {         
                const data = new FormData();
                data.append('upload', file);
                this.xhr.send(data);
            }
        }
    
        function MyCustomUploadAdapterPlugin(editor) {
            editor.plugins.get('FileRepository').createUploadAdapter = (loader) => {
                
                const fieldId = editor.sourceElement.getAttribute('id');
             
                return new MyUploadAdapter(loader, fieldId);
            };
        }
    
        ClassicEditor.create(document.querySelector('#editor_1'), {
            extraPlugins: [MyCustomUploadAdapterPlugin]
        })
            .catch(error => {
                console.error(error);
            });
    
        ClassicEditor.create(document.querySelector('#editor_2'), {
            extraPlugins: [MyCustomUploadAdapterPlugin]
        })
            .catch(error => {
                console.error(error);
            });
    
    
    </script>
    

    accept method:

    public async Task<JsonResult> DocUploadImage()
    {
        var fieldId = HttpContext.Request.Headers["X-FieldId"].ToString();
    
    
        return Json("OK");
    }
    

    When I send the image:
    enter image description here

    I can get the corresponding element id in the request header:

    enter image description here
    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search