vue elementui springboot 上传文件

vue部分:

 
                
                  选取文件
                  
只能上传小于2M的jpg/png/excel/word/txt/ppt/pdf文件

相应的js:

data() {
    return {
      fileList: [], // 用来存放上传的文件
      experiment: {      
        file: '',
      },
      },
  },

methods:{
 beforeRemove(file) {
      return this.$confirm(`确定移除 ${file.name}?`);
    },
    beforeUpload(file) {
      // 将要上传的值赋给experiment,当然也可以直接通过Url传递,看具体需求
      this.experiment.file = file;
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 2MB!');
      }
      return isLt2M;
    },
    afterRemove() {
      this.fileList = [];
      this.experiment.file = '';
    },
}

 

上传触发的方法:

 const fd = new FormData();
    fd.append('reportFile', reportFile);
    fd.append('experimentReport', JSON.stringify(experimentReport));
    const config = {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    };
    return this.$axios.$put(experimentReportUri.updateUrl, fd, config);

后台controller:

  @PutMapping
    ResponseEntity updateReport(KeycloakAuthentication principal,
                                @RequestParam(value = "experimentReport") String experimentReport,
                                @RequestParam(value = "reportFile", required = false) MultipartFile reportFile) throws IOException;

 主要代码:

        String staticPath = ResourceUtils.getURL("classpath:static").getPath();
        // 获取static文件的路径 F:/workplace/ideaPlace/imbs-e/target/classes/static
        staticPath = staticPath.substring(1);
        System.out.println("获取static文件夹的路径 "+staticPath);
        String fileName = reportFile.getOriginalFilename();

        //将(年-月-日)作为文件夹
        LocalDate now = LocalDate.now();
        // now().toString()  2019-11-14
        String uploadFoldName = staticPath + File.separator + now.toString();
        //创建文件夹
        File uploadFold = new File(uploadFoldName);
        if (!uploadFold.exists() || !uploadFold.isDirectory()) {
            // 如果不存在或者不是文件夹 则创建文件夹
            uploadFold.mkdirs();
        }
        //上传文件到指定目录(因为linux和windows标识符不同\和/,所以用File.separator)
        File file = new File(uploadFold + File.separator + fileName);
        reportFile.transferTo(file);
        // 获取最后保存的路径 F:\workplace\ideaPlace\imbs-e\target\classes\static\2019-11-13\jixu.txt
        String getSavePath = file.getAbsolutePath();
        System.out.println("文件保存的本地路径为:"+getSavePath);
        // 前端访问的路径    \static\2019-11-13\jixu.txt
        String getWebPath = getSavePath.substring(getSavePath.lastIndexOf("static") - 1);
        System.out.println("前端访问的uri为:"+getWebPath);

 

 

你可能感兴趣的:(vue,elementUI,springBoot)