在初始的Tinymce-vue中,图片是通过转换为base64的方式进行呈现,但是这种方式在写入数据库的时候,非常不友好,把图片放数据库,下一步就是把视频和压缩包放进去了。
1 2 3 4 |
images_upload_handler: blobInfo => new Promise(resolve => { const img = `data:image/jpeg;base64,${blobInfo.base64()}` resolve(img) }) |
所以,我们需要修改成以URL的形式上传到后端,代码非常简洁,可以参考。
1 2 3 4 5 6 7 8 9 |
images_upload_handler: blobInfo => new Promise((resolve, reject) => { const formData = new FormData() formData.append('file', blobInfo.blob()) api.post('/files/article_img_update', formData).then(res => { resolve('https://blog.lanluo.cn/' + res.data) }).catch(err => { reject(err.msg) }) }) |
定义file,post传递到后端,后端返回的参数中带有URL即可,随后resolve返回给前端进行呈现。
最后附一下官方文档的完整示例:
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 |
const example_image_upload_handler = (blobInfo, progress) => new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.withCredentials = false; xhr.open('POST', 'postAcceptor.php'); xhr.upload.onprogress = (e) => { progress(e.loaded / e.total * 100); }; xhr.onload = () => { if (xhr.status === 403) { reject({ message: 'HTTP Error: ' + xhr.status, remove: true }); return; } if (xhr.status < 200 || xhr.status >= 300) { reject('HTTP Error: ' + xhr.status); return; } const json = JSON.parse(xhr.responseText); if (!json || typeof json.location != 'string') { reject('Invalid JSON: ' + xhr.responseText); return; } resolve(json.location); }; xhr.onerror = () => { reject('Image upload failed due to a XHR Transport error. Code: ' + xhr.status); }; const formData = new FormData(); formData.append('file', blobInfo.blob(), blobInfo.filename()); xhr.send(formData); }); tinymce.init({ selector: 'textarea', // change this value according to your HTML images_upload_handler: example_image_upload_handler }); |
原创文章,作者:蓝洛水深,如若转载,请注明出处:https://blog.lanluo.cn/11864