springboot将文件响应给前端

获取当前项目路径

System.out.println(System.getProperty("user.dir"));

将文件放入响应流

/**
     * 响应体加入文件流
     *
     * @param response
     * @param filePath 文件从盘符开始的完整路径
     */
    public static void buildExcelDocument(HttpServletResponse response, String filePath) {
          
   
        log.debug("文件流filePath:" + filePath);
        //该方法是判断字符串中是否有子字符串。如果有则返回true,如果没有则返回false。
        if (filePath.contains("%")) {
          
   
            try {
          
   
                filePath = URLDecoder.decode(filePath, "UTF-8");
                System.out.println(filePath);
            } catch (UnsupportedEncodingException e) {
          
   
                log.debug("响应流解码错误:" + e.toString());
            }
        }
        ServletOutputStream out = null;
        FileInputStream in = null;
        try {
          
   
            in = new FileInputStream(new File(filePath));
            String[] dir = filePath.split("/");
            String fileName = dir[dir.length - 1];
            String[] array = fileName.split("[.]");
            String fileType = array[array.length - 1].toLowerCase();
            //设置文件ContentType类型、图片类型
            if ("jpg,jepg,gif,png".contains(fileType)) {
          
   
                response.setContentType("image/" + fileType);
                //pdf类型
            } else if ("pdf".contains(fileType)) {
          
   
                response.setContentType("application/pdf");
            } else {
          
   
                //自动判断下载文件类型
                response.setContentType("multipart/form-data");
            }
            out = response.getOutputStream();
            // 读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
          
   
                out.write(buffer, 0, len);
            }
            out.flush();
            response.setStatus(200);
        } catch (FileNotFoundException e) {
          
   
            log.error("error:FileNotFoundException:" + e.toString());
        } catch (Exception e) {
          
   
            log.error("error:" + e.toString());
        } finally {
          
   
            try {
          
   
                assert out != null;
                out.close();
                in.close();
            } catch (NullPointerException e) {
          
   
                log.error("close error:NullPointerException:" + e.toString());
            } catch (Exception e) {
          
   
                log.error("close error:Exception:" + e.toString());
            }
        }
    }
经验分享 程序员 微信小程序 职场和发展