SuNew_bee 2020-06-06 15:13 采纳率: 0%
浏览 1113

springboot用responseEntity下载xlsx文件到客户端时出现问题了

下载文件的service实现

public ResponseEntity export(String s,String pathName) {
        if (s == null) {
            return null;
        }
        FileSystemResource fileSystemResource =  new FileSystemResource(s);
        HttpHeaders headers = new HttpHeaders();
        headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
        headers.add("Content-Disposition","attachment;filename="+pathName);
        headers.add("Pragma", "no-cache");
        headers.add("Expires", "0");
        headers.add("Last-Modified", new Date().toString());
        headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        try {
            return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + pathName).contentLength(fileSystemResource.contentLength())
                    .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
                    .body(new InputStreamResource(fileSystemResource.getInputStream()));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

接口(在调用service层之前调用了生成xlsx文件的代码,大佬们可以略过那里)

public ResponseEntity exportExcel(String pathName){
        List<Casereportform> list = null;
        try{
            list = caseReportFormService.findCaseFormAll();
            System.out.println(list);
        }catch (Exception e){
            e.printStackTrace();
        }
        try {
            XSSFWorkbook xssfWorkbook = exportService.exportExcel(list);
            String uuidFileName= UUID.randomUUID().toString().replace("-","");
            uuidFileName = uuidFileName + ".xlsx";
            FileOutputStream fileOutputStream = new FileOutputStream(uuidFileName);
            //将文件写到服务器中
            xssfWorkbook.write(fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
            xssfWorkbook.close();
            File file = new File(uuidFileName);
            //获取服务器的中的文件
            ResponseEntity responseEntity = exportService.export(uuidFileName,pathName);
            // 路径为文件且不为空则进行删除,将服务器的文件删除以免占用过多资源
            if (file.isFile() && file.exists()) {
                file.delete();
            }
            //将responseEntity作为返回值返回
            return responseEntity;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return  null;
    }

测试结果:
图片说明

它返回一堆乱码,但是却没有下载文件,各位大佬帮忙看看呗。

  • 写回答

2条回答 默认 最新

  • 高建伟-joe 2020-07-24 22:39
    关注

    用blob对象接收下载就可以了

    评论

报告相同问题?

悬赏问题

  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 关于#python#的问题:自动化测试
  • ¥20 问题请教!vue项目关于Nginx配置nonce安全策略的问题