java后台下载文件,前端处理流生成文件

后台将流输出到浏览器,前端获取流,并设置文件名等信息。

后台

public void download(HttpServletResponse response, byte[] data, String showFileName) {

        BufferedInputStream bis = null;
        OutputStream os = null;
        BufferedOutputStream bos = null;
        try {
            os = response.getOutputStream(); // 重点突出
            bos = new BufferedOutputStream(os);
            // 对文件名进行编码处理中文问题
            String fileName = new String( showFileName.getBytes("gb2312"), "ISO8859-1");
            response.reset(); // 重点突出
            response.setCharacterEncoding("UTF-8"); // 重点突出
            response.setContentType("application/x-msdownload");// 不同类型的文件对应不同的MIME类型 // 重点突出
            // inline在浏览器中直接显示,不提示用户下载
            // attachment弹出对话框,提示用户进行下载保存本地
            // 默认为inline方式
            response.setHeader("Content-Disposition", "attachment; filename="+fileName); // 重点突出
            bos.write(data, 0, data.length);// 将文件发送到客户端

        } catch (Exception ex) {
            ex.printStackTrace();
            throw new RuntimeException(ex.getMessage());
        } finally {
            // 特别重要
            // 1. 进行关闭是为了释放资源
            // 2. 进行关闭会自动执行flush方法清空缓冲区内容
            try {
                if (null != bis) {
                    bis.close();
                    bis = null;
                }
                if (null != bos) {
                    bos.close();
                    bos = null;
                }
                if (null != os) {
                    os.close();
                    os = null;
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex.getMessage());
            }
        }
    }

前端

download(){
         this.getDicts("sys_normal_disable").then(res=>{
          const temp = new Blob([res],{type:"application/vnd.ms-excel"});
          const link = document.createElement("a");
          link.href=URL.createObjectURL(temp);
          link.setAttribute("download","阿萨德.xlsx");
          document.body.appendChild(link);
          link.click();
          link.remove();
         })
      },

 

中文文件名,显示异常问题

http协议规定,header中的内容必须是iso8859-1编码。

下载文件时,设置文件名需要在header中设置,所以必须将文件名的编码转为iso8859-1编码。

            response.setHeader("Content-Disposition",
                    "inline;fileName=\"" + new String(fileName.getBytes("UTF-8"), "ISO8859-1") + "\"");

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
前端下载 Excel 文件,后端需要返回文件,可以按照以下步骤进行处理: 1. 后端根据前端请求参数,生成 Excel 文件,并将文件返回给前端。 2. 前端通过 AJAX 发送请求,请求后端生成 Excel 文件的接口。 3. 后端在接收到请求后,使用相关的库(如 Apache POI)生成 Excel 文件,并将文件返回给前端。 4. 前端在接收到后端返回的文件后,使用 Blob 对象创建一个 URL,并将该 URL 赋给一个 a 标签的 href 属性。 5. 前端再使用 JavaScript 触发该 a 标签的 click 事件,即可下载 Excel 文件。 以下是一个示例的后端代码,使用了 Spring Boot 和 Apache POI 库: ```java @GetMapping("/downloadExcel") public ResponseEntity<byte[]> downloadExcel() throws IOException { // 创建 Excel 工作簿 Workbook workbook = new XSSFWorkbook(); Sheet sheet = workbook.createSheet("Sheet1"); // 创建表头 Row header = sheet.createRow(0); header.createCell(0).setCellValue("姓名"); header.createCell(1).setCellValue("年龄"); // 创建数据行 Row dataRow = sheet.createRow(1); dataRow.createCell(0).setCellValue("张三"); dataRow.createCell(1).setCellValue(20); // 将 Excel 文件写入字节数组输出 ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); workbook.write(outputStream); // 设置响应头 HttpHeaders headers = new HttpHeaders(); headers.add("Content-Disposition", "attachment;filename=test.xlsx"); headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); // 返回响应实体 return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK); } ``` 在前端中,可以使用以下代码实现下载: ```javascript axios.get('/downloadExcel', { responseType: 'blob' }).then(res => { const blob = new Blob([res.data], { type: 'application/vnd.ms-excel' }) const url = URL.createObjectURL(blob) const a = document.createElement('a') a.href = url a.download = 'test.xlsx' a.click() URL.revokeObjectURL(url) }) ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值