如何解决CKEditor 5 使用自定义上传适配器上传图片
我正在使用 Angular 11 和 Spring-Boot 后端实现 CKEditor 5。 我按照 https://ckeditor.com/docs/ckeditor5/latest/framework/guides/deep-dive/upload-adapter.html 实现了自定义图像上传适配器。
在后端,我使用令牌实现了安全性。
正在上传。但是,图片加载不起作用,出现 HTTP 401 错误。
代码如下:
export class CustomUploadAdapter {
public loader: any;
public url: string;
public xhr: XMLHttpRequest;
public token: string;
constructor(
loader
) {
this.loader = loader;
}
upload() {
return new Promise(async (resolve,reject) => {
this.loader.file.then((file) => {
this._initRequest();
this._initListeners(resolve,reject,file);
this._sendRequest(file);
});
});
}
abort() {
if (this.xhr) {
this.xhr.abort();
}
}
_initRequest() {
const xhr = (this.xhr = new XMLHttpRequest());
xhr.open("POST",this.url,true);
this.token = localStorage.getItem("access_token");
this.token = localStorage.getItem("access_token");
xhr.setRequestHeader("Authorization",'Bearer ' + this.token);
xhr.responseType = "json";
}
_initListeners(resolve,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(
response.urls
);
});
if (xhr.upload) {
xhr.upload.addEventListener("progress",(evt) => {
if (evt.lengthComputable) {
loader.uploadTotal = evt.total;
loader.uploaded = evt.loaded;
}
});
}
}
_sendRequest(file) {
const data = new FormData();
data.append("file",file);
this.xhr.send(data);
}
}
export class Component implements OnInit {
@ViewChild('ckeditor',{ static: false })
ckeditor: any;
public configCkeditor = ckeditor5Util.configCkeditor; //configs...
...
public onReady(editor) {
editor.plugins.get("FileRepository").createUploadAdapter = (loader) => {
return new CustomUploadAdapter(loader);
};
...
}
...
}
html {
...
<ckeditor [editor]="editor" (ready)="onReady($event)" formControlName="texto" debounce="500"
[config]="configCkeditor"></ckeditor>
...
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。