文件下载

  @ApiOperation(value = "文件下载")
    @GetMapping("/download")
    public void downLoad(HttpServletResponse response,@Validated @NotNull(message = "reportDailyDownloadReq not be null")   ReportDailyDownloadReq reportDailyDownloadReq) {
        ReportDaily reportDaily = reportDailyService.findReportDailyByDayStringAndReportId(new Date(reportDailyDownloadReq.getDay()), reportDailyDownloadReq.getReportId(),reportDailyDownloadReq.getReportFileTypeEnum());
        if(null==reportDaily){
            throw  new BusinessException(RespCodeEnum.REPORT_DAILY_FILE_RECORD_NOT_FOUND.getCode(),RespCodeEnum.REPORT_DAILY_FILE_RECORD_NOT_FOUND.getMsg());
        }
        String filePath = reportDaily.getReportFile();
        reportDailyService.downLoadFile(response,filePath);
    }
@Override
    public void downLoadFile(HttpServletResponse response, String filePath) {

        File file = new File(filePath);
        if(!file.exists()){
            throw  new BusinessException(RespCodeEnum.REPORT_DAILY_FILE_NOT_FOUND.getCode(),RespCodeEnum.REPORT_DAILY_FILE_NOT_FOUND.getMsg());
        }
        // 开始下载文件
        InputStream in = null;
        try {
            // 1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            // 2.设置文件头:最后一个参数是设置下载文件名
            response.addHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(file.getName(), ENCODING));

            in = new FileInputStream(file);

            // 3.通过response获取ServletOutputStream对象(out)
            int b = 0;
            byte[] buffer = new byte[512];
            while (b != -1) {
                b = in.read(buffer);
                if (b != -1) {
                    //4.写到输出流(out)中
                    response.getOutputStream().write(buffer, 0, b);
                }
            }
        } catch (Exception e) {
            log.error("download failed",e);
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                response.getOutputStream().flush();
            } catch (IOException e) {
                log.error("An exception occurred when releasing the resource",e);
            }
        }
    }

总是有些基础内容用过就忘掉了,缺少总结记录。在此记录下来便于以后查找也为遇到类似问题的人一个小小的帮助。

posted on 2023-04-28 14:19  falcon_fei  阅读(14)  评论(0)    收藏  举报