将文件夹压缩后下载:
@Slf4j
public class Test { private static final String BASE_PATH = "/root/doc/"; private static final String TEMP_PATH = "/root/temp/"; private static final String FILE_NAME = "测试"; @RequestMapping(value = "download", method = RequestMethod.GET, produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<byte[]> download() throws Exception {
fileToZip(BASE_PATH, TEMP_PATH, FILE_NAME);
File file = new File(TEMP_PATH + "//" + FILE_NAME + ".zip");
HttpHeaders headers = new HttpHeaders();
// 为了解决中文名称乱码问题
String fileName = new String(FILE_NAME.getBytes("UTF-8"), "iso-8859-1");
headers.setContentDispositionFormData("attachment", fileName + ".zip");
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
} private static void fileToZip(String sourceFilePath, String zipFilePath, String fileName) throws Exception {
File sourceFile = new File(sourceFilePath);
if (!sourceFile.exists()) {
log.info("{} >>>> is not exists", sourceFilePath);
throw new IotBusinessException(ExceptionDefinition.FILE_PATH_NOT_EXISTS.code, ExceptionDefinition.FILE_PATH_NOT_EXISTS.key, "filePathNotExists");
}
File file = new File(zipFilePath);
if (!file.exists()) {
file.mkdirs();
}
File zipFile = new File(zipFilePath + "/" + fileName + ".zip");
if (zipFile.exists()) {
// zip文件存在, 将原有文件删除
zipFile.delete();
}
// zip文件不存在, 打包
pushZip(sourceFile, sourceFilePath, zipFile);
} private static void pushZip(File sourceFile, String sourceFilePath, File zipFile) throws Exception {
FileInputStream fis;
BufferedInputStream bis = null;
FileOutputStream fos;
ZipOutputStream zos = null;
try {
File[] sourceFiles = sourceFile.listFiles();
if (null == sourceFiles || sourceFiles.length < 1) {
log.info("{} >>>> is null", sourceFilePath);
} else {
fos = new FileOutputStream(zipFile);
zos = new ZipOutputStream(new BufferedOutputStream(fos));
byte[] bytes = new byte[1024 * 10];
for (int i = 0; i < sourceFiles.length; i++) {
// 创建ZIP实体,并添加进压缩包
ZipEntry zipEntry = new ZipEntry(sourceFiles[i].getName());
zos.putNextEntry(zipEntry);
// 读取待压缩的文件并写进压缩包里
fis = new FileInputStream(sourceFiles[i]);
bis = new BufferedInputStream(fis, 10240);
int read = 0;
while ((read = bis.read(bytes, 0, 10240)) != -1) {
zos.write(bytes, 0, read);
}
}
}
} catch (IOException e) {
e.printStackTrace();
throw e;
} finally {
try {
if (null != bis) {
bis.close();
}
if (null != zos) {
zos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}