ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
``` /** * @author 张跃帅 * @Description: 文件下载-工具 * @date 2020/08/12 */ @Slf4j public class DownloadUtil { /** * 下载文件 */ public static void download(HttpServletResponse response, File file) { // 下载文件 DownloadUtil.download(response, FileUtil.readBytes(file), file.getName()); } /** * 下载文件-自定义文件名 */ public static void download(HttpServletResponse response, File file, String fileName) { // 下载文件 DownloadUtil.download(response, FileUtil.readBytes(file), fileName); } /** * 下载文件 */ private static void download(HttpServletResponse response, byte[] fileBytes, String fileName) { try { // 设置header response.setHeader("Content-Disposition", "attachment; filename=" + URLUtil.encode(fileName)); response.addHeader("Content-Length", "" + fileBytes.length); response.setHeader("Access-Control-Allow-Origin", "*"); // 添加Access-Control-Expose-Headers,否则前端无法获取下载的文件名称 response.setHeader("Access-Control-Expose-Headers", "Content-Disposition"); // 设置内容类型使用"application/octet-stream"更标准 response.setContentType("application/octet-stream; charset=UTF-8"); // 写入 IoUtil.write(response.getOutputStream(), true, fileBytes); } catch (IOException e) { log.error(">>> 下载文件失败:{}", e.getMessage()); } } }