通过IO流下载文件

2022-06-14 15:17:05 浏览数 (1)

在用流下载pdf的时候易出现中文名称乱码的问题,这里做一个记录

代码语言:javascript复制
 @GetMapping("downloadPdf")
    @ApiOperation("下载pdf文件测试")
    public ResponseBean downloadPdf( HttpServletRequest request, HttpServletResponse response) throws Exception {
        response.setCharacterEncoding("UTF-8");
        String pdfPath = "D:\test.pdf";
        String fileName = "test.pdf";
        File file = new File(pdfPath);
        InputStream in = new FileInputStream(file);
        response.setContentType("application/pdf");
        response.setHeader("Content-disposition", "attachment;filename="    new String(fileName.getBytes("utf-8"),"ISO8859-1"));
        OutputStream ouputStream = response.getOutputStream();
        if(!file.exists()){
            return  ResponseBean.error("未找到文件,请先生成");
        }
        IOUtils.copy(in,ouputStream);
        return new ResponseBean(ResponseCodeEnum.SUCCESS.getCode(), "下载成功");

    }

中文乱码的设置: response.setHeader("Content-disposition", "attachment;filename=" new String(fileName.getBytes("utf-8"),"ISO8859-1"));

这里使用IOUtils同时需要引入一个jar包

代码语言:javascript复制
  <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.4</version>
  </dependency>

下载excel(需引入poi的jar包)

代码语言:javascript复制
   public void exportExcel(HttpServletResponse response,@RequestParam(value = "mntOrgName",required = false) String mntOrgName ) throws IOException {
        response.setCharacterEncoding("UTF-8");
        mntOrgName = mntOrgName == null ? null : mntOrgName.trim();
        List<MntOrg> list = mntTeamOrgService.searchAll(mntOrgName);
        HSSFWorkbook wb = new HSSFWorkbook();
        HSSFSheet sheet = wb.createSheet("测试信息表");

        HSSFRow titleRow = sheet.createRow(0);
        // 设置单元格的宽度
        for (int i = 0; i < 4; i  ) {
            sheet.setColumnWidth(i, 9000);

        }

        titleRow.createCell(0).setCellValue("名称");
        titleRow.createCell(1).setCellValue("电话");
        titleRow.createCell(2).setCellValue("传真");
        // titleRow.createCell(4).setCellValue("描述");
        for (MntOrg mntOrg : list) {
            HSSFRow dataRow = sheet.createRow(sheet.getLastRowNum()   1);
            dataRow.createCell(0).setCellValue(mntOrg.getMntOrgName());
            dataRow.createCell(1).setCellValue(mntOrg.getContactNo());
            dataRow.createCell(2).setCellValue(mntOrg.getFax());
        }
        String filename = DateUtil.getNowDate()   ".xls";
        response.setContentType("application/vnd.ms-excel");
        response.setHeader("Content-disposition", "attachment;filename=" filename);
        OutputStream ouputStream = response.getOutputStream();
        wb.write(ouputStream);
        ouputStream.flush();
        ouputStream.close();
    }
jar

0 人点赞