当前位置:   article > 正文

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

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>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

注意: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'});
        }
        )
      },
.....
	}
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66

后端代码

@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
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/繁依Fanyi0/article/detail/458280
推荐阅读
相关标签
  

闽ICP备14008679号