SpringBoot下载文件的两种方式

20 篇文章 0 订阅
12 篇文章 0 订阅

方式一:HttpServletResponse放在请求参数上

导出Excel

/**
     * 导出数据
     * @return
     */
    @RequestMapping( value = "/do" , method = RequestMethod.POST)
    public void exportData(@RequestBody ExportInfoParam param, HttpServletResponse response) throws IOException {

        XSSFWorkbook workbook = new XSSFWorkbook();
        //创建一个Excel表单,参数为sheet的名字
        XSSFSheet sheet = workbook.createSheet(param.getListName());
        String columnCodes = param.getColumnCodes();
        String columnNames = param.getColumnNames();
        columnNames = "序号,"+columnNames;
        String columnDictCodes = param.getColumnDictCodes();
        if (StringUtils.isEmpty(columnCodes) || StringUtils.isEmpty(columnNames)) {
            throw new IllegalArgumentException("请定义导出列");
        }
        String[] codes = columnCodes.split(",");
        String[] names = columnNames.split(",");
        String ids = param.getIds();
        if (StringUtils.isNotEmpty(ids)) {
            param.setIdss(ids.split(","));
        }

        // 设置列名头部
        setSimpleTitle(workbook, sheet, names, 0, true);

        // 第2行开始
        int rowNum = 1;
        List<ExportInfoResult> resultList = complaintInfoService.findExportList(param);

        //新增数据行,并且设置单元格数据
        for (ExportInfoResult exportInfo : resultList) {
            Map<String, Object> complaintInfoMap = BeanUtil.beanToMap(exportInfo);
            XSSFRow row = sheet.createRow(rowNum);
            // 第一列序号
            setDataCell(workbook, sheet, row, 0, rowNum, true);
            for (int i = 0; i < codes.length; i++) {
                String code = codes[i];
                String value = complaintInfoMap.get(code) != null ? String.valueOf(complaintInfoMap.get(code)) : "";
                setDataCell(workbook, sheet, row, i + 1, value, true);
            }
            rowNum++;
        }
        String fileName = param.getListName()+".xls";

        //解决Excel打开文件提示:xxx文件中部分内容有问题。是否让我们尽量尝试恢复
        ByteArrayOutputStream bos=new ByteArrayOutputStream();
        workbook.write(bos);
        byte[] bArray=bos.toByteArray();
        ByteArrayInputStream tempIn = new ByteArrayInputStream(bArray);

        //清空response
        response.reset();
        //设置response的Header
        response.addHeader("Content-Disposition", "attachment;filename="+ fileName);
        OutputStream os = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/vnd.ms-excel;charset=gb2312");
        response.setHeader("Content-Length", String.valueOf(tempIn.available()));
        //将excel写入到输出流中
        workbook.write(os);
        os.flush();
        os.close();
    }

获取服务器文件

@GetResource(name = "附件下载", path = "/downloadEnclosure", requiredLogin = false, requiredPermission = false)
	@ApiOperation(value = "附件下载")
	public void downloadEnclosure(
			@RequestParam("filePath") String filePath,
			HttpServletResponse response
			) {
		Map<String,Object> params = new HashMap<String, Object>();
		params.put("filePath", filePath);
		emmissionsReductionInputService
				.downloadEnclosure(params,response);
	}
public void downloadEnclosure(Map<String, Object> params, HttpServletResponse response) {
		String filePath = (String) params.get("filePath");
		File file = new File(filePath);
		if (file.exists()){//判断文件是否存在
			String fileName = file.getName();
			try {
				fileName = URLEncoder.encode(fileName, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				log.error("文件名编码失败"+e.toString());
			}//encode编码UTF-8 解决大多数中文乱码
            fileName = fileName.replace("+", "%20");//encode后替换空格  解决空格问题
            response.setContentType("application/force-download");//设置强制下载
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName);//设置文件名
            byte[] buff = new byte[1024];// 用来存储每次读取到的字节数组
            //创建输入流(读文件)输出流(写文件)
            BufferedInputStream bis = null;
            OutputStream os = null;
            try {
                os = response.getOutputStream();
                bis = new BufferedInputStream(new FileInputStream(file));
                int i = bis.read(buff);
                while (i != -1) {
                    os.write(buff, 0, buff.length);
                    os.flush();
                    i = bis.read(buff);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (os != null){
                    try {
                        os.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }else {
            log.info("文件不存在.......");
        }
		
	}

方式二:HttpServletResponse不放在请求参数上

@GetResource(name = "下载文档(生成文档)", path = "/download")
    @ApiOperation("下载文档(生成文档)")
    public void download(CommonParam param) throws Exception{
        complaintInfoService.download(param);
    }
public void download(CommonParam param) throws Exception {
        WordInfoResult entity = this.baseMapper.getWordInfo(param.getId());
        if(ToolUtil.isEmpty(entity)){
            throw new ServiceException(20007, "当前投诉件不存在!");
        }

        // 办理部门-业务分类-编号.doc
        String sb = entity.getAtManageDept() + "-" + entity.getBisiTypeGreen2() +
                "-" + entity.getBisiCode() + ".doc";
        String fileName = URLEncoder.encode(sb,"UTF-8");

        HttpServletResponse response = HttpContext.getResponse();
        response.setContentType("application/force-download");// 设置强制下载不打开
        response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);



        ByteArrayInputStream wordBytesInput = null;
        BufferedInputStream bis = null;
        byte[] buffer = new byte[1024];
        try {
            wordBytesInput = new ByteArrayInputStream(WordTemplate.createWordStr(entity).getBytes() );
            bis = new BufferedInputStream(wordBytesInput);
            OutputStream outputStream = response.getOutputStream();
            int i = bis.read(buffer);

            while (i != -1) {
                outputStream.write(buffer, 0, i);
                i = bis.read(buffer);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (wordBytesInput != null) {
                try {
                    wordBytesInput.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值