springboot把 EXCEL 文件以流的形式返回给前端

avatar
作者
猴君
阅读量:0

1.controller层

    @GetMapping(ReviewUrls.API_DOWNLOAD_REVIEW_RESULT)     public Response<Void> downloadReviewResult(HttpServletResponse response) {         resultService.downloadReviewResult(response);         return Response.ok();     } 

2.service层

    public void downloadReviewResult(HttpServletResponse response) {         /*          逻辑:          1. 以文件流的形式返回          */         // [1] 以文件流的形式返回         String filePath = "test.xslx";         try (FileInputStream inputStream = new FileInputStream(filePath);              ServletOutputStream outputStream = response.getOutputStream();         ) {             // 设置请求头             response.setContentType("application/vnd.openxmlformats-officedocument.wordprocessingml.document");             response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));             byte[] buffer = new byte[1024];             int bytesRead;             while ((bytesRead = inputStream.read(buffer)) != -1) {                 outputStream.write(buffer, 0, bytesRead);             }             outputStream.flush();         } catch (Exception e) {             throw new RuntimeException("下载结果失败");         }     } 

广告一刻

为您即时展示最新活动产品广告消息,让您随时掌握产品活动新动态!