后端实现文件下载

本文档介绍如何在后端使用GetMapping处理文件下载请求。最初尝试使用PostMapping时遇到405错误,经过调整,成功实现在指定路径的下载功能。然而,下载的文件存在打开问题,需要进一步排查和修复。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/**
   * 手机号模版Excel文件下载
   */
  @GetMapping("/一个映射路径")
  public boolean excelTplDownload(HttpServletResponse response)
    throws IOException {
    String realName = "text.xls";
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Resource resource= resolver.getResource("/tpl-xlsx/" + realName);
    String fileName = realName;
    response.reset();
    if (resource.exists()) {
      response.setContentType("application/vnd.ms-excel;charset=utf-8");
      // response.setContentType("application/vnd.ms-excel");  //"application/vnd.ms-excel;charset=utf-8"  application/force-download
      response.addHeader("Content-Disposition","attachment;fileName=" + new String(fileName.getBytes("UTF-8"),"iso-8859-1"));

      byte[] buffer = new byte[1024];
      InputStream fis = null;
      BufferedInputStream bis = null;
      fis =  resource.getInputStream();
      response.setContentLength(fis.available());
      try {
        bis = new BufferedInputStream(fis);
        BufferedOutputStream os = new BufferedOutputStream(response.getOutputStream());
        int i = 0;
        while ((i  = fis.read(buffer))!= -1) {
          os.write(buffer, 0, i);
        }
        log.info("下载成功fileName={}", fileName);
        os.flush();
      } catch (Exception e) {
        e.printStackTrace();
      } finally {

        if (bis != null)
        {
          bis.close();
        }

        if (fis != null)
        {
          fis.close();
        }

      }
    }

    return true;
  }

@GetMapping("/一个映射路径")
先写的 PostMapping 一直报错405

文件下下来但是打开有问题,,待整理 要死了

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值