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