返回

前端使用Vue3+SpringBoot+WangEditor上传图片/视频

前端

前言

在开发过程中,经常需要用到图片和视频上传的功能,本文将结合Vue3、SpringBoot和WangEditor来实现图片和视频的上传功能,并且能够在前端实现上传文件的回显。

技术选型

  • 前端框架:Vue3
  • 后端框架:SpringBoot
  • 富文本编辑器:WangEditor

实现步骤

1. 安装依赖

首先,我们需要安装必要的依赖:

npm install vue3 springboot wangEditor@4.6.3

2. 配置SpringBoot

在SpringBoot项目中,我们需要在application.properties文件中配置文件上传的路径:

spring.servlet.multipart.location=/upload/

3. 配置Vue3

在Vue3项目中,我们需要在main.js文件中配置WangEditor:

import Vue from 'vue'
import App from './App.vue'
import WangEditor from 'wangEditor'

Vue.use(WangEditor)

new Vue({
  render: h => h(App),
}).$mount('#app')

4. 实现上传功能

在Vue3组件中,我们可以使用WangEditor来实现上传功能:

<template>
  <div>
    <wang-editor v-model="content" @change="handleChange" />
    <button @click="handleUpload">上传</button>
  </div>
</template>

<script>
import WangEditor from 'wangEditor'

export default {
  data() {
    return {
      content: '',
    }
  },
  methods: {
    handleChange(content) {
      this.content = content
    },
    handleUpload() {
      const formData = new FormData()
      formData.append('file', this.content)

      fetch('/upload', {
        method: 'POST',
        body: formData,
      })
        .then(res => res.json())
        .then(data => {
          console.log(data)
        })
        .catch(err => {
          console.error(err)
        })
    },
  },
}
</script>

5. 实现回显功能

在SpringBoot项目中,我们需要在控制器中实现回显功能:

@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file) {
    String fileName = file.getOriginalFilename();
    String filePath = "upload/" + fileName;

    try {
        file.transferTo(new File(filePath));
    } catch (IOException e) {
        e.printStackTrace();
        return "上传失败";
    }

    return "上传成功";
}

6. 功能展示

本教程的功能展示如下:

  • 上传图片:用户可以选择一张图片,并点击上传按钮,图片将被上传到服务器,并显示在页面上。
  • 上传视频:用户可以选择一段视频,并点击上传按钮,视频将被上传到服务器,并显示在页面上。
  • 上传回显:当用户上传图片或视频后,页面将显示上传的文件。

结语

本教程介绍了如何使用Vue3、SpringBoot和WangEditor实现图片和视频的上传功能,并能够在前端实现上传文件的回显。希望本教程能够对您有所帮助。