Springboot文件下载工具类

该代码定义了一个名为DownloadUtil的类,用于处理HTTP响应以实现文件下载功能。方法包括根据文件路径、文件、输入流或字节数组下载,支持设定文件类型、文件名和在线/离线模式。内部设置了响应头以控制文件下载行为。
摘要由CSDN通过智能技术生成
package com.synda.utils;

import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;

import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

public class DownloadUtil {
    private static final Logger log = LoggerFactory.getLogger(DownloadUtil.class);

    public static void downloadFileByPath(HttpServletResponse response,String filePath,boolean isOnLine){
        setResponse(response,null,filePath,"","",isOnLine);
        download(response,new File(filePath));
    }

    /**
     * 根据文件路径下载文件
     * @param response 相应体
     * @param filePath 文件路径
     * @param contentType 文件类型
     */
    public static void downloadFileByPath(HttpServletResponse response,String filePath,String contentType,boolean isOnLine){
        setResponse(response,null,filePath,contentType,"",isOnLine);
        download(response,new File(filePath));
    }


    /**
     * 根据文件路径下载文件
     * 指定文件名
     * @param response 相应体
     * @param filePath 文件路径
     * @param contentType 文件类型
     * @param fileName 文件名
     */
    public static void downloadFileByPath(HttpServletResponse response,String filePath,String contentType,String fileName,boolean isOnLine){
        setResponse(response,null,filePath,contentType,fileName,isOnLine);
        download(response,new File(filePath));
    }

    /**
     * 下载文件
     * @param response 相应体
     * @param file 文件路径
     */
    public static void downloadFile(HttpServletResponse response,File file){
        setResponse(response,file,"","","",false);
        download(response,file);
    }

    /**
     * 下载文件
     * @param response 相应体
     * @param file 文件路径
     * @param contentType 文件类型
     */
    public static void downloadFile(HttpServletResponse response,File file,String contentType,boolean isOnLine){
        setResponse(response,file,"",contentType,"",isOnLine);
        download(response,file);
    }


    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param file 文件
     * @param contentType 文件类型
     */
    public static void downloadFile(HttpServletResponse response,File file,String contentType,String fileName,boolean isOnLine){
        setResponse(response,file,"",contentType,fileName,isOnLine);
        download(response,file);
    }

    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param inputStream 文件
     * @param contentType 文件类型
     */
    public static void downloadFileByStream(HttpServletResponse response,FileInputStream inputStream,String contentType,String fileName,boolean isOnLine){
        setResponse(response,contentType,fileName,isOnLine);
        download(response,inputStream);
    }

    /**
     * 下载文件 指定文件名
     * @param response 相应体
     * @param data 文件字节
     * @param contentType 文件类型
     */
    public static void downloadFileByByte(HttpServletResponse response,byte[] data,String contentType,String fileName,boolean isOnLine){
        setResponse(response,contentType,fileName,isOnLine);
        download(response,data);
    }



    /**
     * 设置请求头
     * @param response 相应对象
     * @param file 文件,如果不传,则使用文件路径加载
     * @param filePath 文件路径
     * @param contentType 文件头
     * @param fileName 文件名称
     */
    private static void setResponse(HttpServletResponse response,File file,String filePath,String contentType,String fileName,boolean isOnLine){
        if (file==null) file = new File(filePath);
        fileName = StringUtils.hasText(fileName) ? fileName: file.getName();
        setResponse(response,contentType,fileName,isOnLine);
    }

    /**
     * 设置请求头
     * @param response 相应对象
     * @param contentType 文件头
     * @param fileName 文件名称
     */
    private static void setResponse(HttpServletResponse response,String contentType,String fileName,boolean isOnLine){
        contentType = StringUtils.hasText(contentType) ? contentType: "application/octet-stream";
        response.setCharacterEncoding("UTF-8");
        response.setContentType(contentType);
        if (isOnLine){
            response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        }else {
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8));
        }
    }

    private static void download(HttpServletResponse response,File file){
        try {
            FileInputStream fileInputStream = new FileInputStream(file);
            download(response,fileInputStream);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
    private static void download(HttpServletResponse response,byte[] data){
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(data);
        download(response,byteArrayInputStream);
    }

    /** 文件下载工具类 */
    private static void download(HttpServletResponse response,InputStream inputStream){
        byte[] buffer = new byte[1024];
        BufferedInputStream bis = null;
        try {
            bis = new BufferedInputStream(inputStream);
            response.setHeader("Content-Length", String.valueOf(inputStream.available())); // 内容长度
            OutputStream os = response.getOutputStream();
            int i = bis.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bis.read(buffer);
            }
            log.info("File download successfully!");
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
            log.info("File download failed !");
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

synda@hzy

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值