wangeditor 富文本编辑器 上传图片 并且自定义formdata带参(异步获取oss)

757 阅读1分钟
// 富文本编辑器
			creatEditor() {
				let _ = this
				this.editor = new E("#editBindDiv");

				// 上传图片
				this.editor.config.customUploadImg = async (files, insert) => {
					var xhr = new XMLHttpRequest();
					var formdata = new FormData();
					let params = this.uploadOssData
					await this.getOss() //oss
					// 参数放到formdata里面
					for (let i in params) {
						formdata.append(i, params[i]);
					}
					// file文件放到formdata里面
					files.forEach(function(file) {
						formdata.append("file", file);
					});
					xhr.open('POST', 'https://cool-brain.oss-cn-hangzhou.aliyuncs.com'); // 服务器地址
					xhr.send(formdata);
					// 返回数据
					xhr.onreadystatechange = function() {
						if (xhr.readyState === 4) {
							if (xhr.status < 200 || xhr.status >= 300) {
								this.$message.error("图片上传失败");
							}
							let url = 'https://cool-brain.oss-cn-hangzhou.aliyuncs.com/' + params.key // 拼url
							insert(url); // insert 是获取图片 url 后,插入到编辑器的方法
						}
					}
				}
				this.editor.config.height = 500
				this.editor.create();
			},
			// 获取 富文本text
			getEditorText() {
				this.article.content = this.editor.txt.html()
			},
			// 当class有更改
			classChange(id) {
				this.article.classifications = [id]
			},

			// 获取oss
			async getOss() {
				let res = await this.$api.get_oss();
				if (res.code == 1000) {
					let oss = res.data
					// 生成图片名字
					let time = new Date();
					this.key = `${oss.dir}${this.userId}${time.getTime()}.png`;
					this.uploadUrl = oss.host
					this.uploadOssData = {
						'key': this.key, //文件名字
						'policy': oss.policy,
						'signature': oss.signature,
						'success_action_status': '200', //让服务端返回200
						'OSSAccessKeyId': oss.accessid,
						"expire": oss.expire,
						"dir": oss.dir,
					}
				} else {
					this.$message.error(res.msg)
				}
			},