Element-UI上傳組件


前端組件

<template>
  <!--分頁-->
  <div class="block">
      <el-upload
        class="upload-demo"
        action="/serve/api/file/upload"
        ref="upload"
        :before-upload="beforeUpload"
        :on-error="handleError"
        :on-success="handleSuccess"
        :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'],
      fileSize: 10
    }
  },
  methods: {
    // 刪除文件之前的鈎子,參數為當前上傳的文件和已上傳的文件列表
    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) {
          this.$message.warning(`文件 ${fileName} 已刪除`)
          this.getFiles()
        }
      })
    },
    beforeUpload (file) {
      const suffix = StrUtil.lastSubstring(file.name, '.')
      if (suffix === 'doc' || suffix === 'docx') {
        return true
      } else {
        this.$message.error('僅支持上傳doc、docx文件!')
        return false
      }
    },
    handleError (err, file, fileList) {
      console.log('文件上傳失敗信息:')
      console.log(err)
    },
    // 字符串重組
    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……
      
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM