实现文档下载
@Override
public void downloadTranslationFiles(List<String> filePath, HttpServletResponse response) throws IOException {
if (filePath.size() <= 1) {
for (String fp : filePath) {
downloadFilesForOne( fp, response);
}
} else {
downloadFilesForZIP(filePath, response);
}
}
public void downloadFilesForOne(String filePath, HttpServletResponse response) throws IOException {
FileSystemResource fileSystemResource = null;
FileInputStream in = null;
String filename = null;
BufferedInputStream bis = null;
filename = filePath.substring(filePath.lastIndexOf("\\") + 1);
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
fileSystemResource = new FileSystemResource(filePath);
File file = fileSystemResource.getFile();
ServletOutputStream os = response.getOutputStream();
in = new FileInputStream(file);
bis = new BufferedInputStream(in, 1024 * 10);
byte[] buf = new byte[1024 * 10];
int len = 0;
while ((len = bis.read(buf, 0, 1024 * 10)) > 0) {
os.write(buf, 0, len);
}
if (bis != null) {
bis.close();
}
if (in != null) {
in.close();
}
if (os != null) {`在这里插入代码片`
os.close();
}
}
public void downloadFilesForZIP(List<String> filePath, HttpServletResponse response) throws IOException {
OutputStream os = null;
FileSystemResource fileSystemResource = null;
FileInputStream in = null;
ZipOutputStream zos = null;
String FilePath = null;
String filename = null;
BufferedInputStream bis = null;
os = response.getOutputStream();
zos = new ZipOutputStream(os);
String zipFileName = "dataFile.zip";
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(zipFileName, "UTF-8"));
for (String fp : filePath) {
FilePath = fp;
filename = FilePath.substring(FilePath.lastIndexOf("\\") + 1);
fileSystemResource = new FileSystemResource(FilePath);
File file = fileSystemResource.getFile();
ZipEntry zipEntry = new ZipEntry(filename);
zos.putNextEntry(zipEntry);
in = new FileInputStream(file);
bis = new BufferedInputStream(in, 1024 * 10);
byte[] buf = new byte[1024 * 10];
int len = 0;
while ((len = bis.read(buf, 0, 1024 * 10)) > 0) {
zos.write(buf, 0, len);
}
if (bis != null) {
bis.close();
}
if (in != null) {
in.close();
}
if (zos != null) {
zos.closeEntry();
}
}
}