vue+springboot实现文件下载

13 篇文章 0 订阅
8 篇文章 0 订阅

vue前端代码

<a-button type="primary" style="margin-left: 50px" @click="exportConfigures()">导出配置文件</a-button>
exportConfigures(){
      if (this.selectedRows.length==0) {
        alert("请至少选择一条数据");
        return
      }else if(this.selectedRows.length>1){
        alert("只能选择一条数据");
        return
      }
      const arr =[];
      console.log(this.selectedRows);
      this.selectedRows.forEach(p=>{
        arr.push(p.id);
      });
      axios({
        url:'http://localhost:8000/ConfiguresInfo/Configures/exportFigure',
        method:'post',
        data:arr,
        headers:{'Content-Type':'application/json'},
        responseType: 'blob'
      }).then(
        response => {
          const link = document.createElement('a');
          console.log('请求成功了', response.data);
          let blob=new Blob([response.data.data], {
            type: "application/xml;charset=utf-8"
          });
          link.style.display='none';
          // 兼容不同浏览器的URL对象
          const url = window.URL || window.webkitURL || window.moxURL;
          link.href=url.createObjectURL(blob);
          console.log(this.selectedRows[0].name);
          link.setAttribute('download',this.selectedRows[0].name+'.xml');
          document.body.appendChild(link);
          link.click();
          document.body.removeChild(link);
          url.revokeObjectURL(link.href);//销毁url对象
        }
      )
    }

springboot后端代码

@ApiOperation(value = "导出文件",produces = "application/octet-stream")
    @PostMapping("/exportFigure")
    public ResponseEntity<byte[]> exportConfigure(@RequestBody List<Integer> arr, HttpServletResponse response) throws Exception {
        HashMap map = new HashMap();
        arr.forEach(p-> System.out.println("p = " + p));
        List<ConfiguresEntiry> configuresEntiries = configureService.listByIds(arr);
        ConfiguresEntiry configuresEntiry = configuresEntiries.get(0);
        if (CollectionUtils.isNotEmpty(configuresEntiries)) {
                List<Troops> troops = JSON.parseArray(configuresEntiry.getTroops(), Troops.class);
                configuresEntiry.setArr(troops);
                DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
                DocumentBuilder docBuilder = docFactory.newDocumentBuilder();
                // 创建XML文档对象
                Document doc = docBuilder.newDocument();
                org.w3c.dom.Element rootElement = doc.createElement("Units");
                doc.appendChild(rootElement);
                // 创建UnitInfo元素
                Element unitInfo = doc.createElement("UnitInfo");
                rootElement.appendChild(unitInfo);
                for (Troops troops1 : configuresEntiry.getArr()) {
                    Element unit = doc.createElement("Unit");
                    unit.setAttribute("name", troops1.getUnitname());
                    // 设置其他属性
                    unit.setAttribute("iconDir", troops1.getIcon());
                    unit.setAttribute("type", troops1.getType());
                    unit.setAttribute("step", troops1.getNumber().toString());
                    unit.setAttribute("dllName", troops1.getConnect());
                    //unit.setAttribute("camp", attributes[i][3]);
                    // 非所有单位都有range属性,只给有range的单位设置
                    if (StringUtils.isNotBlank(String.valueOf(troops1.getRange()))) {
                        unit.setAttribute("range", String.valueOf(troops1.getRange()));
                    }
                    unitInfo.appendChild(unit);
                }
                // 将XML文档写入文件或输出流(这里仅做字符串格式化输出)
                TransformerFactory transformerFactory = TransformerFactory.newInstance();
                Transformer transformer = transformerFactory.newTransformer();
                DOMSource source = new DOMSource(doc);
                StringWriter writer = new StringWriter();
                File file = new File("D:\\"+configuresEntiry.getName()+".xml");
                StreamResult result = new StreamResult(file);
                transformer.transform(source, result);
                writer.close();
        }
        File file = new File("D:\\"+configuresEntiry.getName()+".xml");
        String name = file.getName();
        FileInputStream fileInputStream = new FileInputStream(file);
        byte[] bytes = new byte[(int) file.length()];
        fileInputStream.read(bytes);
        fileInputStream.close();
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", name = java.net.URLEncoder.encode(file.getName(), "UTF-8"));
        ResponseEntity<byte[]> responseEntity = new ResponseEntity<>(Files.toByteArray(file), headers, HttpStatus.CREATED);
        return  responseEntity;
    }
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一叶飘零晋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值