element upload上传文件

官网地址:https://element.eleme.cn/#/zh-CN/component/upload

HTML

 <el-upload
                 ref="upload"
                 :limit="1"
                 accept=".bin"//接收的文件类型
                 :action="upload.url"//上传地址,data中获取
                 :headers="upload.headers"
                 :file-list="upload.fileList"
                 :on-progress="handleFileUploadProgress"
                 :on-success="handleFileSuccess"
                 :auto-upload="true"//自动上传
> <el-button slot="trigger" size="small" type="primary">选取文件</el-button> <div slot="tip" class="el-upload__tip">只能上传bin文件</div> </el-upload>

  JS中添加

//data中添加 
// 上传参数
        upload: {
          // 是否禁用上传
          isUploading: false,
          // 设置上传的请求头部
          headers: { Authorization: "Bearer " + getToken() },
          // 上传的地址
          url: '/upgradefile/uploadFile',//访问后台的路径
          // 上传的文件列表
          fileList: []
        },
//方法中添加
this.upload.fileList = [];
// 文件提交处理
submitUpload() {
  this.$refs.upload.submit();
},
// 文件上传中处理
handleFileUploadProgress(event, file, fileList) {
  this.upload.isUploading = true;
},
// 文件上传成功处理
handleFileSuccess(response, file, fileList) {
  if(response.code==200){
    this.upload.isUploading = false;
    this.form.filePath = response.msg;//获取文件路径,这个地方我把文件存储的路径回传在msg中,填充前台页面
  }
  else{
    this.msgError(response.msg)
  }
}

  

  Controller中获取并保存到本地

/**
     * 文件上传
     * @param file
     * @return 保存路径
     * @throws IOException
     */
    @PostMapping("/uploadFile")
    public AjaxResult uploadFile(MultipartFile file) throws IOException {
        String filePath= "E:/temp";
        String filePath1 = FileUploadUtils.upload(filePath,file);//文件保存方法
        return AjaxResult.success(filePath1);
    }

  效果:如下图,选取文件后自动上传,然后返回文件存储路径填充前台页面,之后进行其他处理。

原文地址:https://www.cnblogs.com/webttt/p/14005489.html