angular - CKEditor 5 使用自定义上传适配器上传图像
问题描述
我正在使用带有 Spring-Boot 后端的 Angular 11 实现 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, 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(
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>
...
}
解决方案
推荐阅读
- javascript - 如何使用相同的参数查询 Graphql 2 对象
- elasticsearch - 我想找到子字符串的确切术语,确切的术语不仅仅是术语的一部分
- javascript - 为什么 javascript 在 Google Chrome 中创建填充?
- javascript - 根据属性分解/组合数组
- java - 无法在回收站视图中显示内部子节点值
- ios - 更新应用程序后,iOS 上的本地文件会发生什么情况?
- python - 有没有办法在 django 中提到两个 login_redirect_urls?
- .net - 根据匹配的文本/参数修改 txt 文件中的重复单词/文本
- javascript - Vue js 数据逻辑——预约表
- python - Python - Selenium webdriver 设置 - 消息:未创建会话