阅读量:0
import jakarta.servlet.ServletOutputStream; import jakarta.servlet.http.HttpServletResponse; import lombok.SneakyThrows; import java.io.FileInputStream; import java.net.URLEncoder; import java.nio.charset.StandardCharsets; /** * 功能描述 * * @author jason */ public class DownloadUtil { /** * 下载文件 * * @param response * @param filePath 文件路径 * @param originalName 文件原名 */ @SneakyThrows public static void start(HttpServletResponse response, String filePath, String originalName) { // 读到流中 FileInputStream inputStream = new FileInputStream(filePath);// 文件的存放路径 response.reset(); response.setContentType("application/octet-stream"); response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(originalName, StandardCharsets.UTF_8)); ServletOutputStream outputStream = response.getOutputStream(); int len; byte[] cache = new byte[1024]; // 从输入流中读取一定数量的字节,并将其存储在缓冲区字节数组中,读到末尾返回-1 while ((len = inputStream.read(cache)) > 0) { outputStream.write(cache, 0, len); outputStream.flush(); } inputStream.close(); outputStream.close(); } }