4.Vue上传文件到后端

https://blog.csdn.net/GongWei_/article/details/113120899
一、单文件上传

<!-- multiple  是否支持多选文件  :limit="5"多选限制数  :show-file-list="false  如需要多文件上传el-upload标签加上这三个属性 -->
<el-upload
        class="avatar-uploader"
        action="#"
        :http-request="fileUpload"
    >
    <div class="upload-box">
      <el-button type="minor"><i class="el-icon-upload2"></i></el-button>
    </div>
</el-upload>
<!-- action:''上传文件的接口 -->
fileUpload(uploader){
      // 文件类型校验
      const testmsg = uploader.file.name.substring(uploader.file.name.lastIndexOf(".") + 1);
      const extension = testmsg === "doc" || testmsg === "docx" ;
      if (!extension ) {
        this.$message.warning("上传文件只能是.doc、.docxx格式!");
        return false
      }
      // 文件大小校验
      let size10M = uploader.file.size / 1024 / 1024 < 10
      if(!size10M){
        this.$message.warning('上传大小不能超过10M!')
        return false
      }
      let urlParams = {  //  传给后端的query参数
        level: this.currentObj.level,
        parentId: this.currentObj.id
      }
      // 上传重点  只需要把接口要求的字段以及想对应的值,添加到formData对象里即可  multipartFiles后端定义的key
      let form = new FormData();
      form.append('multipartFiles',uploader.file);
      axios({
        url: `http://10.8.214.46:8088/sys/sysCatalogue/upload`,
        method: "post",
        headers: {//请求头,根据自身需求加或者不加
          Authorization: "",
          "Content-Type": "multipart/form-data",
        },
        params: urlParams,
        data: form,
        onUploadProgress: progressEvent => {//这一步是展示上传的进度条,不展示也行,根据自身需求决定
          let percent=(progressEvent.loaded / progressEvent.total * 100) | 0
          uploader.onProgress({percent:percent});//调用uploader的进度回调
        }
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("上传成功");
          this.getNavList();
        }else{
          this.$message.error('上传失败');
        }
      }).catch((err)=>{
        this.$message.error(err);
      })
    },

二、多文件(word)上传

//  多文件上传用到的防抖函数  utils.js文件
export default {
  debounce(fn,wait) {
    let timer = null;
    return function (...args) {
      if (timer) {
        clearTimeout(timer)
        timer = null
      }
      timer = setTimeout(()=> {
        fn.apply(this, args)
      }, wait)
    }
  }
}
//  这里是多文件上传,为了掉一次接口用了防抖函数  utils.debounce
<el-upload
                class="avatar-uploader"
                action="#"
                :file-list="uploadCfg.fileList"
                :before-upload="handleBeforeUpload"
                :http-request="handleUploadHttp"
                multiple
                :limit="10"
                :show-file-list="false"
              >
              <div class="upload-box">
                <el-button type="minor"><i class="el-icon-upload2"></i>上传</el-button>
              </div>
 </el-upload>

uploadCfg: {
       fileList: [], // 默认绑定的文件列表
       validFileList: [] // 通过校验的文件列表
},

handleBeforeUpload(file){
      let vm = this;
      return new Promise((resolve, reject) => {
        // 收集文件列表
        this.uploadCfg.validFileList.push(file);
        console.log(file,"文件地址")
        // 校验文件列表
        vm.handleDebounceVarifyFile(this.uploadCfg.validFileList);

        setTimeout(function (){
          if (vm.uploadCfg.validFileList.length){
            resolve(true);
          } else {
            reject(true);
          }
        }, 100);
      });
    },
    handleDebounceVarifyFile: utils.debounce(function (){
      console.log(this.uploadCfg.validFileList)
      if (!this.uploadCfg.validFileList.length){
        return;
      }
      const nameList = this.uploadCfg.validFileList.map(v => v.name.substring(v.name.lastIndexOf(".") + 1));
      
      const newList = nameList.filter(v => v!=='doc' || v!=='docx')
      if (newList.length) {
        this.$message.warning("上传文件只能是.doc或.docx格式!");
        return false
      }
    }, 20),
    handleUploadHttp(){
      this.handleDebounceUpload();
    },
    handleDebounceUpload: utils.debounce(function (){
      if (!this.uploadCfg.validFileList.length){
        return;
      }
      //  只需要把接口要求的字段以及想对应的值,添加到formData对象里即可,这里是多文件上传所以用forEach遍历分别添加进formData对象
      let formData = new FormData();
      this.uploadCfg.validFileList.forEach((item_file) =>{
        console.log(item_file)
        formData.append(`multipartFiles`,item_file);
      });
      
      let urlParams = {}
      axios({
        url: this.baseUrl + `/${this.currentObj.navigationId}/batchUpload`,
        method: "post",
        headers: {//请求头,根据自身需求加或者不加
          Authorization: "",
          "Content-Type": "multipart/form-data",
        },
        data: formData,
        params: urlParams,
      }).then((res) => {
        if (res.data.code == 200) {
          this.$message.success("上传成功");
          this.uploadCfg.validFileList = [];
          
        }else{
          this.$message.error('上传失败');
        }
      }).catch((err)=>{
        this.$message.error(err);
        this.uploadCfg.validFileList = [];
      })
    }, 20),
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容