更新数据同步
This commit is contained in:
@@ -85,30 +85,23 @@ public class FileUtils {
|
|||||||
/**
|
/**
|
||||||
* 下载文件核心方法
|
* 下载文件核心方法
|
||||||
*/
|
*/
|
||||||
public static void downloadFile(HttpServletResponse response, File file, String downloadFileName) throws IOException {
|
public static void downloadFile(HttpServletResponse response, File file, String downloadFileName) throws Exception {
|
||||||
// 1. 校验文件合法性
|
String encodedName = URLEncoder.encode(downloadFileName, StandardCharsets.UTF_8);
|
||||||
if (file == null || !file.exists() || !file.isFile()) {
|
// 设置响应头
|
||||||
throw new FileNotFoundException("文件不存在或不是有效文件:" + (file != null ? file.getAbsolutePath() : "null"));
|
response.setContentType("application/octet-stream");
|
||||||
}
|
response.setContentLengthLong(file.length());
|
||||||
if (!file.canRead()) {
|
response.setHeader("Content-Disposition",
|
||||||
throw new IOException("文件无读取权限:" + file.getAbsolutePath());
|
String.format("attachment; filename=\"%s\"; filename*=UTF-8''%s", encodedName, encodedName));
|
||||||
}
|
response.setHeader("Cache-Control", "no-cache");
|
||||||
// 2. 设置响应头(解决中文乱码、触发下载对话框)
|
// 流传输(自动关闭)
|
||||||
response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE); // 二进制流
|
try (InputStream in = new BufferedInputStream(new FileInputStream(file));
|
||||||
String fileName = downloadFileName != null ? downloadFileName : file.getName();
|
OutputStream out = new BufferedOutputStream(response.getOutputStream())) {
|
||||||
// 文件名URLEncoder编码,兼容浏览器中文显示
|
byte[] buf = new byte[4096];
|
||||||
String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
|
|
||||||
response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);
|
|
||||||
response.setContentLengthLong(file.length()); // 设置文件大小(可选,优化体验)
|
|
||||||
// 3. 流传输文件(try-with-resources自动关闭流)
|
|
||||||
try (InputStream in = new FileInputStream(file);
|
|
||||||
OutputStream out = response.getOutputStream()) {
|
|
||||||
byte[] buffer = new byte[1024 * 8]; // 8KB缓冲区,提升传输效率
|
|
||||||
int len;
|
int len;
|
||||||
while ((len = in.read(buffer)) != -1) {
|
while ((len = in.read(buf)) != -1) {
|
||||||
out.write(buffer, 0, len);
|
out.write(buf, 0, len);
|
||||||
}
|
}
|
||||||
out.flush(); // 强制刷出缓冲区数据
|
out.flush();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user