基礎備忘(文件下載)

文件下載

  @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);
            }
        }
    }

總是有些基礎內容用過就忘掉了,缺少總結記錄。在此記錄下來便於以後查找也爲遇到類似問題的人一個小小的幫助。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章