前端组件

<template>
  <!--分页-->
  <div class="block">
     <el-upload
        class="upload-demo"
        action="/serve/api/file/upload"
        ref="upload"
        :on-success="handleSuccess"
        :before-remove="beforeRemove"
        :on-remove="handleRemove"
        :file-list="fileList">
        <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
        <div slot="tip" class="el-upload__tip">支持上传 {{ strRebuild(fileType) }} 格式,且不超过 {{ fileSize }}M</div>
      </el-upload>
    </div>
</template>

<script>
import * as StrUtil from '@/utils/strUtil'
import * as FileApi from '@/api/file'
export default {
  data () {
    return {
      drawer: false,
      fileList: [],
      // 允许的文件类型
      fileType: ['doc', 'docx']
    }
  },
  methods: {
    // 删除文件之前的钩子,参数为当前上传的文件和已上传的文件列表
    beforeRemove (file, fileList) {
      return this.$confirm(`确定删除 ${file.name} ?`)
    },
    // 当前文件上传成功后的钩子函数
    handleSuccess (file, fileList) {
      this.getFiles()
      return this.$message.success(`文件 ${fileList.name} 上传成功`)
    },
    handleRemove (file, fileList) {
      const fileName = file.name
      FileApi.deleteFile(fileName).then(res => {
        if (res.code !== 10000) return this.$message.error('文件删除失败!')
        this.getFiles()
        return this.$message.success('文件删除成功!')
      })
    },
    // 字符串重组
    strRebuild (str) {
      return StrUtil.strRebuild(str)
    },
  }

strUtil.js

// 字符串相关工具类
// 数组根据分隔符重组为字符串
export function strRebuild (arr, split) {
  if ( arr === undefined ||    arr === null || !(arr instanceof Array) || arr.length === 0 ) {
    return ''
  }
  if (split === undefined || split === null) {
    split = ', '
  }
  var str = ''
  arr.forEach((v, i) => {
    if (i === arr.length - 1) {
      str = str + v
    } else {
      str = str + v + split
    }
  })
  return str
}
// 截取最后一个特定字符后面的字符串
export function lastSubstring (str, split) {
  if ( str === undefined || str === null || split === undefined || split === null ) {
    return ''
  }
  return str.substring(str.lastIndexOf(split) + 1)
}

后端接口

@ApiOperation(value = "文件上传接口")
@ApiImplicitParam(name = "file", value = "上传的文件类型为MultipartFile", required = true, paramType = "query")
@PostMapping("/upload")
public R uploadFile(@RequestBody MultipartFile file) {

    // do something……

}
02-14 03:24