private byte[] downloadImages(HttpServletResponse response, String filePath) {
File file = new File(filePath);
response.setHeader("Content-Disposition", "attachment;filename=" + file.getName());
byte[] bytes = null;
try{
bytes = FileUtils.readFileToByteArray(file);
}catch (IOException e){
e.printStackTrace();
}
return bytes;
}
private String compressProcess(Long parkingId, List<String> imageNames){
String path = parkingImagePath;
String parkingDir = "/" + parkingId;
createDirectories(path + parkingDir);
imageNames.forEach(imageName -> copyFiles(path + "/" + imageName, path + parkingDir));
zip(path + parkingDir);
deleteDir(path + parkingDir);
return path + parkingDir + ".zip";
}
private static void createDirectories(String path){
File dateDirectory = new File(path);
dateDirectory.mkdir();
}
private static void copyFiles(String sourceFile, String targetPath){
File source = new File(sourceFile);
File target = new File(targetPath);
try {
FileUtils.copyFileToDirectory(source, target);
}catch (IOException e){
e.printStackTrace();
}
}
private static void zip(String zipPath){
FileOutputStream fos = null;
ZipOutputStream zipOut = null;
try {
fos = new FileOutputStream(zipPath + ".zip");
zipOut = new ZipOutputStream(fos);
File fileToZip = new File(zipPath);
zipFile(fileToZip, fileToZip.getName(), zipOut);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
try {
zipOut.close();
fos.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
private static void zipFile(File fileToZip, String fileName, ZipOutputStream zipOut){
if (fileToZip.isHidden()) {
return;
}
if (fileToZip.isDirectory()) {
File[] children = fileToZip.listFiles();
for (File childFile : children) {
zipFile(childFile, fileName + "/" + childFile.getName(), zipOut);
}
return;
}
FileInputStream fis = null;
try {
fis = new FileInputStream(fileToZip);
ZipEntry zipEntry = new ZipEntry(fileName);
zipOut.putNextEntry(zipEntry);
byte[] bytes = new byte[1024];
int length;
while ((length = fis.read(bytes)) >= 0) {
zipOut.write(bytes, 0, length);
}
}catch (IOException e){
e.printStackTrace();
}finally {
try {
fis.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
private static void deleteDir(String path){
try {
FileUtils.deleteDirectory(new File(path));
} catch (IOException e) {
e.printStackTrace();
}
}
注意:Controller方法上注解添加produces属性
produces = MediaType.APPLICATION_OCTET_STREAM_VALUE