瀏覽代碼

优化下载,并不读取所有的字节再下载,而是边读边下载

sunyj 8 年之前
父節點
當前提交
4e9cc1d202

+ 12 - 0
src/main/java/com/uas/report/service/FileService.java

@@ -132,6 +132,18 @@ public interface FileService {
 	 */
 	public void download(byte[] data, String fileName, HttpServletResponse response);
 
+	/**
+	 * 下载文件
+	 * 
+	 * @param file
+	 *            要下载的文件
+	 * @param fileName
+	 *            下载后的文件名称
+	 * @param response
+	 * @throws IOException
+	 */
+	public void download(File file, String fileName, HttpServletResponse response) throws IOException;
+
 	/**
 	 * 下载文件(支持断点续传)
 	 * 

+ 30 - 11
src/main/java/com/uas/report/service/impl/FileServiceImpl.java

@@ -5,7 +5,6 @@ import java.io.FileFilter;
 import java.io.FileInputStream;
 import java.io.FileNotFoundException;
 import java.io.IOException;
-import java.io.InputStream;
 import java.io.OutputStream;
 import java.net.URI;
 import java.net.URLEncoder;
@@ -262,23 +261,16 @@ public class FileServiceImpl implements FileService {
 			throw new FileNotFoundException("文件不存在:" + filePath);
 		}
 
-		byte[] data = null;
 		String fileName = "";
 		// 下载文件夹之前,需进行压缩
 		if (file.isDirectory()) {
 			fileName = file.getName() + ".zip";
-			data = ZipUtils.zipFolder(filePath, fileFilter);
+			byte[] data = ZipUtils.zipFolder(filePath, fileFilter);
+			download(data, fileName, response);
 		} else {
 			fileName = file.getName();
-			InputStream inputStream = new FileInputStream(file);
-			data = new byte[inputStream.available()];
-			inputStream.read(data);
-			inputStream.close();
-		}
-		if (ArrayUtils.isEmpty(data)) {
-			throw new IOException("下载失败:" + filePath);
+			download(file, fileName, response);
 		}
-		download(data, fileName, response);
 	}
 
 	@Override
@@ -297,6 +289,33 @@ public class FileServiceImpl implements FileService {
 		}
 	}
 
+	@Override
+	public void download(File file, String fileName, HttpServletResponse response) throws IOException {
+		if (file == null) {
+			throw new IllegalArgumentException("参数不能为空:file");
+		}
+		if (!file.exists() || !file.isFile()) {
+			throw new IOException("文件不存在或并非文件");
+		}
+		FileInputStream fis = new FileInputStream(file);
+
+		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
+		ServletOutputStream outputStream = response.getOutputStream();
+		try {
+			byte[] data = new byte[1024];
+			int i;
+			while ((i = fis.read(data)) != -1) {
+				outputStream.write(data, 0, i);
+			}
+			outputStream.flush();
+		} catch (IOException e) {
+			logger.error(e.getMessage());
+			return;
+		} finally {
+			fis.close();
+		}
+	}
+
 	@Override
 	public void rangeDownload(File file, String fileName, HttpServletRequest request, HttpServletResponse response)
 			throws IOException {