element ui+vue+springboot 批量上传文件 前端加后端代码

这次仅仅只是弄这个功能花了三天时间,网上总是零零散散的很多内容,有些有用有些用不上。这次也零零散散的记录一下吧。。 _

前端ui+script

<template>
    <el-upload
          :auto-upload="false"
          multiple
          accept=".jpg,.png,.doc,.docx,.xlsx,.xls"
          class="upload-demo"
          action="#"
          :on-change="uploadChange"
          :before-remove="beforeRemove"
          :on-remove="upLoadRemove"
          :on-preview="downLoadFile"
          :file-list="fileList"
        >
          <el-button size="small" icon="el-icon-plus" slot="trigger"
            >选取文件</el-button
          >
          <el-button
            style="margin-left: 10px"
            size="small"
            icon="el-icon-upload"
            type="success"
            @click="submitUpload"
            :disabled="fileList.length <= 0"
            >上传到服务器</el-button
          >
          <span slot="tip" class="el-upload__tip">支持jpg,png,doc,docx,xlsx,xls格式文件</span>
        </el-upload>

</template>

<script>
import axios from 'axios'
export default {
  // props: ['add_id'],
  computed: {
    // 这里定义上传文件时携带的参数,即表单数据
    upData: function() {
      return this.form
    }
  },
  data() {
    return {
      formLabelWidth: '80px',
      form: {
        username: '',
        age: ''
      },
      file: {
        fileName: "",
        filePath: "",
      },
      fileList: [],
      formData: [],
      // file:''
    }
  },
  methods: {


     // 拖拽上传
     beforeRemove(file, fileList) {
      this.fileList = fileList;
      // return this.$confirm(`确定移除 ${file.name}?`);
    },
    // 移除附件
    upLoadRemove(file, fileList) {
      let tempFileList = [];
      for (var index = 0; index < this.fileList.length; index++) {
        if (this.fileList[index].name !== file.name) {
          tempFileList.push(this.fileList[index]);
        }
      }
      this.fileList = tempFileList;
    },
    // 监控上传文件列表
    uploadChange(file, fileList) {
     
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
     
        // 判断文件名的类型
      if (fileType === 'jpg' || fileType === 'png' || fileType === 'doc' || fileType === 'docx' || fileType === 'xlsx' || fileType === 'xls') {

        let existFile = fileList
          .slice(0, fileList.length - 1)
          .find((f) => f.name === file.name);
        if (existFile) {
          this.$message.error("当前文件已经存在!");
          fileList.pop();
        }
        this.fileList = fileList;
      } else { 
        this.$message.error("上传模板只能是jpg,png,doc,docx,xlsx,xls格式!");
          fileList.pop();
        return
      }
      
      

     
    },
    // 上传到服务器  formidable接收
    async submitUpload() {
      var _this=this
      // 上传文件大小不能超过100MB!
      const isLt100M = this.fileList.every(
        (file) => file.size / 1024 / 1024 < 100
      );
      let formData = new FormData();
      //注意此处是item.raw,如果直接使用files,那么不会有数据传输到后端
      this.fileList.forEach((item) => {
        formData.append("files", item.raw);
      });
      
      // 新建到数据表中
      // formData.append("add_id", add_id);
     //这里的xxxx是自己的后端上传地址
     //此处的formData不要加花括号{},不然无法传输数据
      axios
      .post("xxxxxxxx",formData,{
          headers: {
            "Content-Type": "multipart/form-data"
          }
        })
        .then(res => {
          $('#picpath').val('')
          console.log(res)
          if (res.data.reslut == 0) {
            // _this.fileList= [];
            alert('保存成功!')
            //  用来返回保存的数据
         
           var fileName=res.data.datalist
            var tempPath = res.data.filePath.replace(/\\/g, "/");

            // 解析路径
            console.log(this.getFileName(tempPath))

            this.$emit('for_path', fileName)
          }
        })
        .catch(error => {
         
          alert('保存失败,请稍后重试')
        })
     
    },
    // 点击文件进行下载
    downLoadFile(file) {
      var a = document.createElement("a");
      var event = new MouseEvent("click");
      a.download = file.name;
      a.href = file.url;
      a.dispatchEvent(event);
    },

    // 解析路径
    getFileName(path){
        var pos1 = path.lastIndexOf('/');
        var pos2 = path.lastIndexOf('\\');
        var pos  = Math.max(pos1, pos2);
        if( pos<0 )
            return path;
        else
            return path.substring(pos+1);
    }








    },
   

  

  


  
}
</script>

后端Springboot

	//这里的xxxx是自己的后端上传地址
    //上传服务事件解析xls,保存到数据库
    @RequestMapping(value = "xxxxxxxx", produces = "text/html;charset=UTF-8", method = RequestMethod.POST)
    @ResponseBody
    public ReslutData upCqltjtCustomer( @RequestParam("files") MultipartFile [] files,
                                       HttpServletRequest request) throws Exception {
        ReslutData reslutData = new ReslutData();
    		//具体代码逻辑实现功能区,由读者完善吧。
        return reslutData;
    }

你可能感兴趣的:(前端,vue.js,ui,java,后端)