应用springboot实现文件下载

本地文件下载(须要文件的绝对路径)

步骤一封装文件下载api工具类:
@Slf4j@Componentpublic class CommonDownLoadUtil {    /** * @param response 客户端响应 * @throws IOException io异样 */ public void downLoad(HttpServletResponse response, String downloadUrl) throws Throwable {        if (Objects.isNull(downloadUrl)) {            // 如果接管参数为空则抛出异样,由全局异样解决类去解决。            throw new NullPointerException("下载地址为空"); }        // 读文件        File file = new File(downloadUrl);        if (!file.exists()) {            log.error("下载文件的地址不存在:{}", file.getPath());            // 如果不存在则抛出异样,由全局异样解决类去解决。 throw new HttpMediaTypeNotAcceptableException("文件不存在"); }        // 获取用户名        String fileName = file.getName();        // 重置response        response.reset();        // ContentType,即通知客户端所发送的数据属于什么类型        response.setContentType("application/octet-stream; charset=UTF-8");        // 取得文件的长度        response.setHeader("Content-Length", String.valueOf(file.length()));        // 设置编码格局        response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(fileName, "UTF-8"));        // 发送给客户端的数据        OutputStream outputStream = response.getOutputStream();        byte[] buff = new byte[1024];        BufferedInputStream bis = null;        // 读取文件        bis = new BufferedInputStream(new FileInputStream(new File(downloadUrl)));        int i = bis.read(buff);        // 只有能读到,则始终读取        while (i != -1) {            // 将文件写出            outputStream.write(buff, 0, buff.length);            // 刷出            outputStream.flush();            i = bis.read(buff);        }    }}

备注:

  • 本文将工具类加了@Component交给spring治理了,当然,也能够将此办法应用静态方法封装。
  • 本文的全局异样解决,能够抉择try->catch,也能够应用全局异样解决类去解决(全局异样具体看上文)。
  • 将工具类封装之后,则能够应用了,这里代码的调用,本文就不再叙述了。