今天帮同事解决了一个angular文件下载的问题


问题描述:

     使用Java做后台,augularJs做前端,需要下载后端传的文件流,在前端获取不到文件名,前端请求使用angular自带的http包,@angular/common/http,client.d.ts文件下的HttpClient类。

    参考了 https://blog.csdn.net/m0_48030026/article/details/109443483 这篇博文给了思路,然后使用了 HttpClient类中的下边代码段方法

 

get(url: string, options: {
        headers?: HttpHeaders | {
            [header: string]: string | string[];
        };
        observe: 'response';
        params?: HttpParams | {
            [param: string]: string | string[];
        };
        reportProgress?: boolean;
        responseType: 'blob';
        withCredentials?: boolean;
    }): Observable>;

调用的方式为:

 public getMainDate() { return this.http.get("/exchKZReport/getMonths", {observe: 'response', responseType: 'blob'}); } 

然后在返回值中直接找header中内容即可。

附一段后端的代码

/**
     * 
     * exportReport:  TODO excel导出 
     * @author: zhaozm
     * @Date: 2021年9月24日 上午11:03:09 
     * @param request
     * @param response
     */
    public void exportReport(HttpServletRequest request, HttpServletResponse response
            , SaleCostRequestVO params) {
        //获取查询数据,在service层实现
        List list = queryCostReport(params).getPayload();

        HSSFWorkbook wb = new HSSFWorkbook();//声明工
        Sheet sheet = wb.createSheet("销售量与成本分析表");//新建表
        sheet.setDefaultColumnWidth(15);//设置表宽
        HSSFCellStyle style = wb.createCellStyle();
        org.apache.poi.hssf.usermodel.HSSFFont font = wb.createFont();
        font.setFontHeightInPoints((short) 12);
        HSSFCellStyle headerStyle = wb.createCellStyle();
        org.apache.poi.hssf.usermodel.HSSFFont headerFont = wb.createFont();
        headerFont.setFontHeightInPoints((short) 14);
//        headerFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
//        headerStyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);
        headerStyle.setFont(headerFont);
//        CellRangeAddress cra0 = new CellRangeAddress(0, 1,0,9);
//        sheet.addMergedRegion(cra0);
//        sheet.setDefaultColumnWidth((short) 15);
//        Row row = sheet.createRow(0);
//        Cell cell1 = row.createCell(0);
//
//        cell1.setCellValue("数据权限申请审批表");
//        cell1.setCellStyle(headerStyle);
        //设置字体样式
        org.apache.poi.hssf.usermodel.HSSFFont titleFont = wb.createFont();
//        titleFont.setBoldweight(HSSFFont.BOLDWEIGHT_BOLD);
        style.setFont(titleFont);
//        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);

        Row row1 = sheet.createRow(0);
        Cell cell = row1.createCell(0);
        cell.setCellValue("GDS");
        cell.setCellStyle(style);
        cell = row1.createCell(1);
        cell.setCellValue("代理人PCC号");
        cell.setCellStyle(style);
        cell = row1.createCell(2);
        cell.setCellValue("代理人IATA号");
        cell.setCellStyle(style);
        cell = row1.createCell(3);
        cell.setCellValue("代理人名称");
        cell.setCellStyle(style);
        cell = row1.createCell(4);
        cell.setCellValue("销售国家/地区");
        cell.setCellStyle(style);
        cell = row1.createCell(5);
        cell.setCellValue("办事处");
        cell.setCellStyle(style);
        cell = row1.createCell(6);
        cell.setCellValue("责任区");
        cell.setCellStyle(style);
        cell = row1.createCell(7);
        cell.setCellValue("航班号");
        cell.setCellStyle(style);
        cell = row1.createCell(8);
        cell.setCellValue("航段");
        cell.setCellStyle(style);
        cell = row1.createCell(9);
        cell.setCellValue("订座量");
        cell.setCellStyle(style);
        cell = row1.createCell(10);
        cell.setCellValue("取消量");
        cell.setCellStyle(style);
        cell = row1.createCell(11);
        cell.setCellValue("净订座量");
        cell.setCellStyle(style);
        cell = row1.createCell(12);
        cell.setCellValue("取消率");
        cell.setCellStyle(style);
        cell = row1.createCell(13);
        cell.setCellValue("订座成本");
        cell.setCellStyle(style);
        cell = row1.createCell(14);
        cell.setCellValue("单位成本");
        cell.setCellStyle(style);
        cell = row1.createCell(15);
        cell.setCellValue("出票数");
        cell.setCellStyle(style);
        cell = row1.createCell(16);
        cell.setCellValue("卡授权数");
        cell.setCellStyle(style);
        cell = row1.createCell(17);
        cell.setCellValue("出票成本");
        cell.setCellStyle(style);
        cell = row1.createCell(18);
        cell.setCellValue("总成本");
        cell.setCellStyle(style);
        cell = row1.createCell(19);
        cell.setCellValue("销售金额");
        cell.setCellStyle(style);
//      cell = row1.createCell(8);
//      cell.setCellValue("最小值");
//      cell = row1.createCell(9);
//      cell.setCellValue("最小值时间");
//      cell.setCellStyle(style);
        //时间转字符串的格式
//        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (int i = 0, imax = list.size(); i < imax; i++) {
            row1 = sheet.createRow(i + 1);
            row1.createCell(0).setCellValue(list.get(i).getGdsName());
            row1.createCell(1).setCellValue(list.get(i).getPccNo());
            row1.createCell(2).setCellValue(list.get(i).getAgentNo());
            row1.createCell(3).setCellValue(list.get(i).getAgentName());
            row1.createCell(4).setCellValue(list.get(i).getCountryCode());
            row1.createCell(5).setCellValue(list.get(i).getSaleCity());
            row1.createCell(6).setCellValue(list.get(i).getLiabilityRegion());
            row1.createCell(7).setCellValue(list.get(i).getFltNo());
            row1.createCell(8).setCellValue(list.get(i).getOriDes());
            row1.createCell(9).setCellValue(list.get(i).getTotalAmount());
            row1.createCell(10).setCellValue(list.get(i).getCancelAmount());
            row1.createCell(11).setCellValue(list.get(i).getNetAmount());
            row1.createCell(12).setCellValue(list.get(i).getCancelRate());
            row1.createCell(13).setCellValue(list.get(i).getBookingCost());
            row1.createCell(14).setCellValue(list.get(i).getUnitCost());
            row1.createCell(15).setCellValue(list.get(i).getNetTktNum());
            row1.createCell(16).setCellValue(list.get(i).getCcAuthNum());
            row1.createCell(17).setCellValue(list.get(i).getNetTktCost());
            row1.createCell(18).setCellValue(list.get(i).getTotalCost());
            row1.createCell(19).setCellValue(list.get(i).getSalesAmount());

        }
        
        response.reset();
        response.setContentType("application/msexcel;charset=UTF-8");
        try {
//            SimpleDateFormat newsdf=new SimpleDateFormat("yyyyMMddHHmmss");
//            String date = newsdf.format(new Date());
            String fileName = "销售量与成本分析表" +  ".xls";
            String finalFileName = null;
            final String userAgent = request.getHeader("USER-AGENT");
            if(StringUtils.contains(userAgent, "MSIE")){//IE浏览器
                finalFileName = URLEncoder.encode(fileName,"GBK");
            }else if(StringUtils.contains(userAgent, "Mozilla")){//google,火狐浏览器
                finalFileName = new String(fileName.getBytes(), "ISO8859-1");
            }else{
                finalFileName = URLEncoder.encode(fileName,"GBK");//其他浏览器
            }
            response.addHeader("Content-Disposition", "attachment;filename=\""
                    + finalFileName + "\"");
            OutputStream out = response.getOutputStream();
            wb.write(out);
            out.flush();
            out.close();
            wb.close();
        } catch (FileNotFoundException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
    }

如果前端还是没找到文件名,可以参考如下博文:

https://www.cnblogs.com/nanamiao/p/9407576.html

主要内容为在response.addHeader时增加如下代码

response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");

 以上为本次问题记录。