Ant Design Pro + springboot实现文件上传功能

前端代码

<a-upload
  :fileList="fileList"
  :beforeUpload="beforeUpload"
  :customRequest="customRequest"
>
  <a-button style="margin-left: 50px" type="primary" ref="btn">导入配置文件 </a-button>
</a-upload>

注意:fileList 、 beforeUpload、customRequest需要放在data中。

data(){
	return{
.....
 fileList:[],
 beforeUpload:(file,UpFileList)=>{
        // file:上传单个文件时候的文件内容,UpFileList:上传多个文件时的文件内容组成的数组
        // 1、控制文件数量
        if (this.fileList.length + UpFileList.length > 10) {
          this.$message.warning('超过文件上传数量限制');
          // 设置上传的文件为错误状态
          file.status = 'error';
          return false
        };
        // 2、控制上传的文件大小
        if (file.size > 1073741824) {
          this.$message.warning('文件大小超过最大限度1G');
          file.status = 'error';
          return false
        };
        // 3、控制上传文件不能为空
        if (file.size === 0) {
          this.$message.warning('所选信息中存在空文件或目录,请重新选择')
          file.status = 'error';
          return false
        };
        // 4、控制已上传文件不重复
        this.fileList.map(item=>{
          if(item.name===file.name){
            this.$message.warning('不允许重复上传');
            file.status = 'error';
            return false
          }
        })
      },
 customRequest:file=>{
        const form = new FormData();
        form.append('file',file.file);
        console.log("=",file.file);
        axios({
          url:'http://localhost:8000/ConfiguresInfo/Configures/uploadFigure',
          method:'post',
          data:form,
          headers:{'Content-Type':'multipart/form-data'},
        }).then(
          response => {
            //console.log()
            console.log("请求成功",response.data);
            if (response.data.code==200){
              alert("解析成功");
              this.$router.push({ path: '/fastcomfigure/fast'});
              this.$refs.table.refresh(true);
            }else {
              alert("文件格式错误,请重新上传文件");
              this.$refs.table.refresh(true);
            }
          },
          error =>{
            console.log(error.mesage);
            alert("文件格式错误,请重新上传文件");
            this.$router.push({ path: '/fastcomfigure/fast'});
        }
        )
      },
.....
	}
}

后端代码

@ApiOperation(value = "导入文件")
    @PostMapping("/uploadFigure")
    public HashMap uploadConfigure(@RequestPart("file") MultipartFile file) throws Exception {
        Logger logger = LoggerFactory.getLogger(getClass());
        ConfiguresEntiry configuresEntiry = new ConfiguresEntiry();
        configuresEntiry.setOperateName("admin");
        configuresEntiry.setCreateTime(new Date());
        try (InputStream inputStream = file.getInputStream()) {
            parseAndPopulateConfiguresEntiry(file.getOriginalFilename(), inputStream, configuresEntiry);
            configureService.save(configuresEntiry);
            return createSuccessResponse();
        } catch (IOException | ParserConfigurationException | SAXException e) {
            logger.error("Failed to process uploaded configure file", e);
            return createFailureResponse(e);
        }
    }
    private void parseAndPopulateConfiguresEntiry(String originalFilename, InputStream inputStream,
                                                  ConfiguresEntiry configuresEntiry) throws Exception {
        String[] split = originalFilename.split("\\.");
        configuresEntiry.setName(split[0]);
        configuresEntiry.setFileformat("xml");
        ArrayList<Troops> troopsList = new ArrayList<>();
        Document doc = buildDocument(inputStream);
        NodeList unitNodes = doc.getElementsByTagName("Unit");
        for (int i = 0; i < unitNodes.getLength(); i++) {
            Element unitElement = (Element) unitNodes.item(i);
            Troops troops = new Troops();
            troops.setId(String.valueOf(i + 1));
            troops.setConnect(unitElement.getAttribute("dllName"));
            troops.setIcon(unitElement.getAttribute("iconDir"));
            troops.setUnitname(unitElement.getAttribute("name"));
            troops.setType(unitElement.getAttribute("type"));
            troops.setNumber(Integer.valueOf(unitElement.getAttribute("step")));
            if (unitElement.hasAttribute("range")) {
                troops.setRange(Integer.valueOf(unitElement.getAttribute("range")));
            }
            troopsList.add(troops);
        }
        configuresEntiry.setTroops(JSON.toJSONString(troopsList));
    }
    private Document buildDocument(InputStream inputStream) throws Exception {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        return dBuilder.parse(inputStream);
    }
    private HashMap createSuccessResponse() {
        HashMap  response = new HashMap<>();
        response.put("code", 200);
        response.put("message", "success");
        return response;
    }
    private HashMap createFailureResponse(Exception s) {
        HashMap response = new HashMap<>();
        response.put("code", 500);
        response.put("message", s);
        return response;
    }

相关推荐

  1. (图片)文件功能实现

    2024-04-24 07:34:04       57 阅读
  2. springmvc实现文件功能

    2024-04-24 07:34:04       32 阅读
  3. uniapp实现文件和图片选择功能实现

    2024-04-24 07:34:04       35 阅读
  4. Ant Design Pro + springboot实现文件功能

    2024-04-24 07:34:04       34 阅读
  5. 在 Spring Boot 中实现文件功能

    2024-04-24 07:34:04       35 阅读
  6. vue3+springboot+minio,实现文件功能

    2024-04-24 07:34:04       24 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-04-24 07:34:04       98 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-04-24 07:34:04       106 阅读
  3. 在Django里面运行非项目文件

    2024-04-24 07:34:04       87 阅读
  4. Python语言-面向对象

    2024-04-24 07:34:04       96 阅读

热门阅读

  1. 算法设计与优化——向量中数据唯一化

    2024-04-24 07:34:04       32 阅读
  2. K8s: 控制器之StatefulSets对象

    2024-04-24 07:34:04       29 阅读
  3. flutter 解决ExpandableText组件三个点调整颜色问题

    2024-04-24 07:34:04       31 阅读
  4. 爬虫 Selector 选择器查找元素

    2024-04-24 07:34:04       30 阅读
  5. 系统架构设计

    2024-04-24 07:34:04       37 阅读
  6. 第三章、汇编2

    2024-04-24 07:34:04       30 阅读