如何给Tinymce-vue自定义图片上传接口,images_upload_handler示例

243次阅读

共计 3011 个字符,预计需要花费 8 分钟才能阅读完成。

在初始的 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
});

 

正文完