实现文件下载功能, 适用于 Java Web 项目;

代码

package cn.zzzykj.util;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 文件下载工具类
 * @author Lenovo
 */
public class FileDownUtil {

    private static final Logger log = LoggerFactory.getLogger(FileDownUtil.class);

    /**
     * 通过输入流下载文件
     * @param response 响应对象
     * @param stream 输入流
     * @param fileName 文件名
     * @param isDown 是否下载
     */
    public static void down(HttpServletResponse response, InputStream stream, String fileName, boolean isDown) {
        log.info("通过输入流下载文件:{}", fileName);
        if (isDown) {
            response.setHeader("Content-Disposition", "attachment;filename=" + Convert.convertCharset(fileName, CharsetUtil.UTF_8, CharsetUtil.GBK));
        } else {
            response.setHeader("Content-Disposition", fileName);
        }
        try {
            IoUtil.copy(stream, response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("下载文件失败");
        }
    }

    /**
     * 通过文件下载文件
     * @param response 响应对象
     * @param file 文件
     * @param isDown 是否下载
     */
    public static void down(HttpServletResponse response, File file, boolean isDown) {
        log.info("下载文件:{}", file);
        if (isDown) {
            response.setHeader("Content-Disposition", "attachment;filename=" + Convert.convertCharset(file.getName(), CharsetUtil.UTF_8, CharsetUtil.GBK));
        } else {
            response.setHeader("Content-Disposition", file.getName());
        }
        try {
            IoUtil.copy(new FileInputStream(file), response.getOutputStream());
            response.flushBuffer();
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException("下载文件失败");
        }
    }

    /**
     * 通过文件下载文件
     * @param response 响应对象
     * @param path 文件路径
     * @param isDown 是否下载
     */
    public static void down(HttpServletResponse response, String path, boolean isDown) {
        File file = new File(path);
        down(response, file, isDown);
    }
}

依赖项


<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.7.22</version>
</dependency>

发表评论