springboot+vue3 集成wangEditor 5 富文本图片的上传和下载

前端

1. 依赖

pnpm install @wangeditor/editor --save
pnpm install @wangeditor/editor-for-vue@next --save

2. 在template使用wangEditor 5

  • v-model:富文本中用户输入的内容
<!--最外层的div必须要有-->
<div style="border: 1px solid #ccc">
 <Toolbar
   style="border-bottom: 1px solid #ccc"
   :editor="editorRef"
   :mode="mode"
 />
 <Editor
   style="height: 500px; overflow-y: hidden;"
   v-model="content" 
   :mode="mode"
   :defaultConfig="editorConfig"
   @onCreated="handleCreated"
 />
</div>

3. js代码部分

  • customInsert这个配置的作用:发送图片到接口后返回的只有图片的文件名,但是要在editor中显示图片需要图片完整的url,这里就是把url补完整
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import {onBeforeUnmount, reactive, shallowRef} from "vue";
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'
/* wangEditor5 初始化开始 */
const editorRef = shallowRef()  // 编辑器实例,必须用 shallowRef
const mode = 'default'
{ placeholder: '请输入内容...',MENU_CONF: {}}
// 图片上传配置
editorConfig.MENU_CONF['uploadImage'] = {
  headers: {
    token: '',	
  },
  server: import.meta.env.VITE_BASE_API + "/avatar/wang/upload",  // 服务端图片上传接口
  fieldName: 'file',  // 服务端图片上传接口参数名
  // 后端返回的图片地址不是完整的,可以在这里补全
  customInsert: (res, insertFn) => {
    const baseUrl = import.meta.env.VITE_BASE_API ; // 你要添加的前缀字符串
    const imageUrl = res.data[0].url;
    const newImageUrl = baseUrl + imageUrl;
    insertFn(newImageUrl);
  },
}
// 组件销毁时,也及时销毁编辑器,否则可能会造成内存泄漏
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})
// 记录 editor 实例,重要!
const handleCreated = (editor) => {
  editorRef.value = editor
}

2. 后端

1. 后端图片的上传和下载接口 controller层

// 下载
  @RequestMapping("/download/{imgPath}")
  public void download(@PathVariable("imgPath") String fileName, HttpServletResponse response) {
    String UPLOAD_PATH = System.getProperty("user.dir") + "/avatar/" + fileName;
    FileUtilCustom.downloadFile(UPLOAD_PATH, response);
  }
 // wangeditor 指定的上传,返回值比较特殊
  @PostMapping("/wang/upload")
  public Map<String, Object> wangEditorUpload(MultipartFile file) {
    String UPLOAD_PATH = System.getProperty("user.dir") + "/avatar/";
    String fileName = FileUtilCustom.uploadFile(file, UPLOAD_PATH);

    Map<String, Object> resMap = new HashMap<>();
    // wangEditor上传图片成功后, 需要返回的参数
    resMap.put("errno", 0);
    resMap.put("data", CollUtil.newArrayList(Dict.create().set("url", "/avatar/download/" +  fileName)));
    return resMap;
  }

2. 接口中调用的上传和下载的方法

// 自己写的上传和下载,还需要再优化
import cn.hutool.core.io.FileUtil;
import com.example.exception.CustomException;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;

import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.UUID;

public class FileUtilCustom {
  /**
   * 文件上传,将文件file放到指定的filePath位置
   * @param file 文件
   * @param filePath 保存文件的绝对路径
   * @return  文件名
   * @throws CustomException 自定义异常,文件上传失败
   */
  public static String uploadFile(MultipartFile file, String filePath) {
    if (file.isEmpty()) {
      return "文件为空";
    }
    if (!FileUtil.isDirectory(filePath)) {
      FileUtil.mkdir(filePath);
    }
    try {
      // 截取UUID的前10位,防止文件名重复
      String fileName = UUID.randomUUID().toString().substring(0,10)+'_' + file.getOriginalFilename();
      FileUtil.writeBytes(file.getBytes(), filePath + fileName);
      return fileName;	// 上传成功后只返回文件名
    }catch (Exception e){
      throw new CustomException("文件上传失败");
    }
  }

  /**
   * 文件下载
   * @param filePath  文件的绝对路径
   * @param response  响应
   * @throws CustomException 自定义异常,文件不存在,文件下载失败
   */
  public static void downloadFile(String filePath, HttpServletResponse response) {
    if (!FileUtil.exist(filePath)) {
      throw new CustomException("文件不存在");
    }
    try {
      String fileName = FileUtil.getName(filePath);
      // 文件名可能包含中文对文件名进行编码
      String encodeName =
        URLEncoder.encode(fileName, StandardCharsets.UTF_8);
      // 设置响应头,需要在跨域设置中,设置"Content-Disposition"
      response.setHeader("Content-Disposition", "attachment'filename=" + encodeName );
      response.setContentType("application/octet-stream");
      OutputStream outputStream = response.getOutputStream();
      FileUtil.writeToStream(filePath, outputStream);
      outputStream.close();
    }catch (Exception e){
      throw new CustomException("文件下载失败");
    }
  }
}

评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值