我唯一知道的就是自己无知。——苏格拉底最有学问和最有见识的人总是很谨慎的——卢梭

我们昨天接入了wangEditor富文本编辑器

今天我们试着将阿里云OSS集成进wangEditor

首先我们先使用vue在页面渲染结束后调用初始化wangEditor

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OSS上传Demo</title>
<link href="/css/elementUI.css" rel="stylesheet">
<script src="/js/jquery-3.5.1.min.js"></script>
<script src="/js/vue.min.js"></script>
<script src="/js/elementUI.js"></script>
<script src="/js/singleUpload.js"></script>
<script src="/js/wangEditor.min.js"></script>
</head>
<body>
<div class="myApp" id="myapp">
<div>
<single-upload ref="singleUpload" v-model="imageUrl"></single-upload>
文件url:{{imageUrl}}
</div>
<div>
<div id="myEditor"></div>
<el-button @click="showHtml" type="primary">预览</el-button>
<div v-html="editorHtml"></div>
</div>
</div>
<script>
new Vue({
el: '#myapp',
data: {
imageUrl: '',
editor: null,
editorHtml: ''
},
created() {
this.$nextTick(() => {
// 注意这玩意只能在页面加载完毕后调,如果在vue的created直接调用,会导致上方工具栏失效!!!
// 这是vue写法
this.initWangEditor()
})
},
methods: {
initWangEditor() {
let E = window.wangEditor;
this.editor = new E("#myEditor");
this.editor.config.customUploadImg = wangEditorCustomUploadImg
this.editor.config.zIndex = 1
this.editor.create()
},
showHtml() {
this.editorHtml = this.editor.txt.html()
}
}
})
</script>
</body>
</html>

image-20210621221353491

注意下面有一句

1
this.editor.config.customUploadImg = wangEditorCustomUploadImg

这里指向的方法,我们在singleUpload.js中定义了

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
function policy() {
return new Promise((resolve, reject) => {
$.ajax({
url: '/oss',
type: 'GET',
contentType: 'application/json; charset=UTF-8',
success: function (res) {
if (res.code == 20000) {
resolve(res)
} else {
reject(res)
}
},
error: function (res) {
reject(res)
}
});
});
}

function getUUID() { //生成UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
}

function wangEditorCustomUploadImg(resultFiles, insertImgFn) {
// resultFiles 是 input 中选中的文件列表
// insertImgFn 是获取图片 url 后,插入到编辑器的方法
policy().then(response => {
if (response.code != 20000) {
console.error(response)
return
}
console.log(response)
let key = response.data.dir + getUUID() + "_${filename}";
let url = response.data.host + "/" + key.replace("${filename}", resultFiles[0].name)
let formData = new FormData();
formData.append('key', key); //存储在oss的文件路径
formData.append('ossaccessKeyId', response.data.accessid); //accessKeyId
formData.append('policy', response.data.policy); //policy
formData.append('signature', response.data.signature); //签名
formData.append("dir", response.data.dir);
formData.append("host", response.data.host);
formData.append("file", resultFiles[0]);
console.log(url)
$.ajax({
url: response.data.host,
type: 'POST',
contentType: false,
processData: false,
data: formData,
success: function (res) {
// 上传图片,返回结果,将图片插入到编辑器中
insertImgFn(url)
},
error: function (res) {
console.error(res)
}
})
}).catch(err => {
console.error(err)
});
}

Vue.component('singleUpload', {
props: ['value'],
template: ' <div class="single-upload">' +
' <el-upload' +
' :before-upload="beforeUpload"' +
' :data="dataObj"' +
' :file-list="fileList"' +
' :multiple="false"' +
' :on-preview="handlePreview"' +
' :on-remove="handleRemove"' +
' :on-success="handleUploadSuccess"' +
' :show-file-list="showFileList"' +
' :action="dataObj.host"' +
' list-type="text"' +
' style="display: flex;"' +
' >' +
' <el-button size="small" type="primary">点击上传</el-button>' +
' </el-upload>' +
' <el-dialog :modal="false" :visible.sync="dialogVisible">' +
' <img width="100%;" v-if="isImg(fileList[0].url)" :src="fileList[0].url" alt="图片找不到了..."/>' +
' <video width="900px" controls autoplay muted v-if="isVideo(fileList[0].url)" :src="fileList[0].url" alt="视频找不到了..."/>' +
' </el-dialog>' +
' </div>',
data() {
return {
dataObj: {
policy: "",
signature: "",
key: "",
ossaccessKeyId: "",
dir: "",
host: ""
// callback:'',
},
dialogVisible: false
};
},
computed: {
imageUrl() {
return this.value;
},
imageName() {
if (this.value != null && this.value !== "") {
return this.value.substr(this.value.lastIndexOf("/") + 1);
} else {
return null;
}
},
fileList() {
return [
{
name: this.imageName,
url: this.imageUrl
}
];
},
showFileList: {
get: function () {
return (
this.value !== null && this.value !== "" && this.value !== undefined
);
},
set: function (newValue) {
}
}
},
methods: {
isVideo() {
let fileType = this.getFileType()
return ~['.mp4', '.avi'].indexOf(fileType)
},
isImg() {
let fileType = this.getFileType()
return ~['.png', '.jpg', '.jpeg', '.gif'].indexOf(fileType)
},
getFileType() {
let fileType = this.value.substring(this.value.lastIndexOf('.'))
return fileType
},
getUUID() { //生成UUID
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
return (c === 'x' ? (Math.random() * 16 | 0) : ('r&0x3' | '0x8')).toString(16)
})
},
emitInput(val) {
this.$emit("input", val);
},
handleRemove(file, fileList) {
this.emitInput("");
},
handlePreview(file) {
this.dialogVisible = true;
},
beforeUpload(file) {
let _self = this;
return new Promise((resolve, reject) => {
policy()
.then(response => {
console.log(response)
_self.dataObj.policy = response.data.policy;
_self.dataObj.signature = response.data.signature;
_self.dataObj.ossaccessKeyId = response.data.accessid;
_self.dataObj.key = response.data.dir + this.getUUID() + "_${filename}";
_self.dataObj.dir = response.data.dir;
_self.dataObj.host = response.data.host;
resolve(true);
})
.catch(err => {
reject(false);
});
});
},
handleUploadSuccess(res, file) {
console.log("上传成功...");
this.showFileList = true;
this.fileList.pop();
this.fileList.push({
name: file.name,
url:
this.dataObj.host +
"/" +
this.dataObj.key.replace("${filename}", file.name)
});
this.emitInput(this.fileList[0].url);
console.log(this.fileList[0]);
}
}
})

然后即可实现功能,我们测试一下

image-20210621221745164

项目源码:

https://gitee.com/VampireAchao/simple-oss.git