比較簡單,有一個customUploadImg鈎子函數:
const editor = new Editor(this.$refs.editorcontainer); editor.config.height = 300; editor.config.customUploadImg = async (files, insertImgFn) => { for (let file of files) { const param = new FormData(); param.append("file", file); const res = await this.$http.post( buildUrl("/sys/oss/upload", false), param, { headers: { "Content-Type": "multipart/form-data" }, } ); insertImgFn(res.data.data.url); } };
這里順便記錄一下在還沒有服務器時,如何讓圖片僅僅顯示在本地,方法也同樣是在這里調用 insertImgFn 方法,這個方法接收一個字符串的url,然后會自動在當前光標位置插入一個img標簽,src即是傳入 insertImgFn 的url,只要它是一個可顯示的url即可。那么意思就是本地的blob url也是可以的了,所以這里有如下兩種方式直接顯示本地圖片。
方法一:
for (let file of files) { insertImgFn(URL.createObjectURL(file)); }
方法二:
for (let file of files) { const r = new FileReader(); r.readAsDataURL(file); r.onload = function () { insertImgFn(r.result); }; }
補充一些課外知識:
Blob是瀏覽器內支持的高級JS對象,File繼承自Blob,所以File也是一種Blob,Blob如何獲取暫且不管,File如何獲取呢?最常見是通過input標簽來獲取:
<input type="file" onchange="showFile(this)"> <script> function showFile(input) { let file = input.files[0]; alert(`File name: ${file.name}`); // 例如 my.png alert(`Last modified: ${file.lastModified}`); // 例如 1552830408824 } </script>
上面的file即是File的一個對象實例,為什么是input.files[0]?回憶一下,選擇文件的時候有時是不是可以多選?多選了數組就會有多個成員,單選的話就只有一個成員。
以上是通常的獲取File實例的方式,在wangEditor里,customeUploadImg鈎子方法也會傳進來File的數組,里面都是File實例。剛剛說了,File實例也是Blob,有了Blob,我們有兩種方法把它變成可被src或者href接收的東西:
URL.createObjectURL(file)
FileReader 的 readAsDataURL
以上,備忘。