|
@@ -7,6 +7,7 @@ import javax.servlet.ServletOutputStream;
|
|
|
import javax.servlet.http.HttpServletResponse;
|
|
|
import java.io.File;
|
|
|
import java.io.FileInputStream;
|
|
|
+import java.io.FileOutputStream;
|
|
|
import java.io.IOException;
|
|
|
import java.net.URLEncoder;
|
|
|
import java.util.Calendar;
|
|
@@ -45,6 +46,66 @@ public class JyResponseUtil {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ public static void exportAndSaveFile(String fileName, File sourceFile, String targetDir, HttpServletResponse response) {
|
|
|
+ ServletOutputStream out = null;
|
|
|
+ FileInputStream fin = null;
|
|
|
+ FileOutputStream fout = null;
|
|
|
+
|
|
|
+ try {
|
|
|
+ // 检查源文件是否存在以及是否可以读取
|
|
|
+ if (sourceFile == null || !sourceFile.exists() || !sourceFile.canRead()) {
|
|
|
+ throw new IOException("源文件不存在或不可读: " + sourceFile.getAbsolutePath());
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建输入流读取源文件
|
|
|
+ fin = new FileInputStream(sourceFile);
|
|
|
+
|
|
|
+ // 设置响应头,以浏览器下载方式处理该文件
|
|
|
+ response.setCharacterEncoding("utf-8");
|
|
|
+ response.setContentType("application/octet-stream; charset=UTF-8");
|
|
|
+ String encodedFileName = URLEncoder.encode(fileName, "UTF-8").replaceAll("\\+", "%20");
|
|
|
+ response.setHeader("Content-Disposition", "attachment;filename=" + encodedFileName);
|
|
|
+
|
|
|
+ out = response.getOutputStream();
|
|
|
+
|
|
|
+ // 创建目标文件并检查目录是否存在
|
|
|
+ File targetFile = new File(targetDir, fileName);
|
|
|
+ if (!targetFile.getParentFile().exists()) {
|
|
|
+ targetFile.getParentFile().mkdirs(); // 如果目标文件夹不存在,则创建
|
|
|
+ }
|
|
|
+
|
|
|
+ // 创建输出流写入目标文件
|
|
|
+ fout = new FileOutputStream(targetFile);
|
|
|
+
|
|
|
+ // 使用4KB的缓冲区读取文件并同时写入浏览器和目标文件
|
|
|
+ byte[] buffer = new byte[4096]; // 4KB缓冲区
|
|
|
+ int bytesToRead;
|
|
|
+
|
|
|
+ while ((bytesToRead = fin.read(buffer)) != -1) {
|
|
|
+ out.write(buffer, 0, bytesToRead); // 写入浏览器
|
|
|
+ fout.write(buffer, 0, bytesToRead); // 写入目标文件
|
|
|
+ }
|
|
|
+
|
|
|
+ // 确保所有数据已发送到客户端和目标文件
|
|
|
+ out.flush();
|
|
|
+ fout.flush();
|
|
|
+
|
|
|
+ System.out.println("文件已成功导出并保存到: " + targetFile.getAbsolutePath());
|
|
|
+
|
|
|
+ } catch (Exception e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
|
|
|
+ } finally {
|
|
|
+ try {
|
|
|
+ if (fin != null) fin.close();
|
|
|
+ if (fout != null) fout.close();
|
|
|
+ if (out != null) out.close();
|
|
|
+ } catch (IOException e) {
|
|
|
+ e.printStackTrace();
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
|
|
|
/**
|
|
|
* 获取当前时间年月日
|