使用WangEditor富文本编辑器上传图片时,如果您的图片下载接口需要携带请求头,则直接使用URL插入图片会失败。本文将指导您如何解决这个问题。
问题:许多开发者在使用WangEditor时,发现直接使用类似process.env.vue_APP_BASE_API + ‘/file/dwn2?fileName=’ + result[0]这样的方式拼接接口地址来插入图片无效,因为接口需要特定的请求头。尝试将图片下载到本地再获取blob也无法解决问题。
根本原因:WangEditor的默认图片上传机制无法处理需要请求头的接口。简单的URL拼接无法传递必要的请求头信息。
解决方案:需要自定义WangEditor的图片上传功能,在自定义函数中手动处理请求头,并把获取到的图片数据传递给WangEditor。
具体步骤:
-
查阅WangEditor文档: 仔细阅读WangEditor官方文档中关于自定义图片上传的章节。这部分文档详细说明了如何自定义上传函数。
-
自定义上传函数: 使用fetch或axios等工具,编写一个自定义的图片上传函数。在这个函数中:
- 发送包含所需请求头的请求到您的图片下载接口。
- 处理接口返回的图片数据,将其转换为WangEditor可接受的格式,例如Base64编码或Blob。
- 使用WangEditor提供的API将图片数据插入到编辑器中。
示例代码(使用fetch): (请根据您的实际接口和请求头进行调整)
// 自定义上传函数 const customUpload = async (result) => { const url = process.env.VUE_APP_BASE_API + '/file/dwn2?fileName=' + result[0]; const headers = { // 添加您的请求头 'Authorization': 'Bearer your_token', // ... other headers }; try { const response = await fetch(url, { headers }); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const blob = await response.blob(); const reader = new FileReader(); reader.onload = (e) => { // 将Blob转换为Base64 const base64 = e.target.result; // 使用WangEditor API插入图片 (具体方法请参考WangEditor文档) editor.cmd.insertHTML(`@@##@@`); }; reader.readAsDataURL(blob); } catch (error) { console.error('图片上传失败:', error); // 处理上传错误 } }; // 将自定义上传函数配置到WangEditor editor.customConfig.uploadImgServer = customUpload; editor.create();
通过自定义上传函数,您可以完全控制图片上传流程,确保请求头被正确传递,从而成功在WangEditor中插入图片。 记住替换示例代码中的占位符为您的实际值。 请参考WangEditor的官方文档获取关于其API的更详细的信息。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END