1: zip tool class
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class ZipUtil {<!-- -->
/**
* Set the return front-end file name
* @param response response
* @param fileName file name, including suffix
* @return OutputStream
* @throws Exception Exception
*/
public static OutputStream getOutputStreamFileName(HttpServletResponse response, String fileName) throws Exception{<!-- -->
response.reset();
String fileType = fileName.split("\.")[1].toLowerCase();
switch (fileType){<!-- -->
case "doc":
response.setContentType("application/msword");//Set the generated file type
break;
case "docx":
response.setContentType("application/msword");//Set the generated file type
break;
case "xls":
response.setContentType("application/vnd.ms-excel");//Set the generated file type
break;
case "xlsx":
response.setContentType("application/vnd.ms-excel");//Set the generated file type
break;
case "pdf":
response.setContentType("application/pdf");//Set the generated file type
break;
case "zip":
response.setContentType("application/zip");//Set the generated file type
break;
case "dbf":
response.setContentType("application/x-dbf");//Set the generated file type
break;
default:
return response.getOutputStream();
}
response.setCharacterEncoding("UTF-8");//Set the file header encoding method and file name
response.setHeader("Content-Disposition", "attachment;filename=" +
new String(URLEncoder.encode(fileName, "UTF-8").getBytes("utf-8"), "ISO8859-1"));
return response.getOutputStream();
}
/**
* Compressed file
* @param response response
* @param filePath file path
* @param fileName Compression generated file name
* @throwsIOExceptionIOException
*/
public static void zipDateFile(HttpServletResponse response, String filePath, String fileName) throws Exception {<!-- -->
if (StringUtils.isEmpty(filePath) || !new File(filePath).exists()) return;
zipDateFile(response, getAllFile(filePath), fileName, true);
}
/**
* Compressed file
* @param response response
* @param fileList file collection
* @param fileName Compression generated file name
* @throwsIOExceptionIOException
*/
public static void zipDateFile(HttpServletResponse response, List<File> fileList, String fileName, boolean deleteSourceFile) throws Exception {<!-- -->
getOutputStreamFileName(response, fileName);
ServletOutputStream servletOutputStream = response.getOutputStream();
ZipOutputStream zipOutputStream = new ZipOutputStream(servletOutputStream);
zipFile(fileList, zipOutputStream, true);
try {<!-- -->
zipOutputStream.close();
} catch (IOException e) {<!-- -->
log.error("Stream closing failed", e);
}
}
/**
* Compressed export
* @param fileList file list
* @param zipOutputStream zip stream
* @throwsIOExceptionIOException
*/
public static void zipFile(List<File> fileList, ZipOutputStream zipOutputStream, boolean deleteSourceFile) throws IOException {<!-- -->
byte[] buffer = new byte[1024];
for (File file : fileList) {<!-- -->
if (file.exists()) {<!-- -->
if (file.isFile()) {<!-- -->
try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));) {<!-- -->
zipOutputStream.putNextEntry(new ZipEntry(file.getName()));
int size = 0;
while ((size = bis.read(buffer)) > 0) {<!-- -->
zipOutputStream.write(buffer, 0, size);
}
zipOutputStream.closeEntry();
} finally {<!-- -->
if(deleteSourceFile) file.delete();
}
} else {<!-- -->
File[] files = file.listFiles();
if(null == files) continue;
List<File> childrenFileList = Arrays.asList(files);
zipFile(childrenFileList, zipOutputStream, deleteSourceFile);
}
}
}
}
/**
* Get all files in the specified folder, excluding files in the folder
* @param filePath file path
* @return fileList
*/
public static List<File> getAllFile(String filePath) {<!-- -->
if (StringUtils.isEmpty(filePath)) return null;
return getAllFile(new File(filePath));
}
/**
* Get all files in the specified folder, excluding files in the folder
* @param dirFile folder
* @return fileList
*/
public static List<File> getAllFile(File dirFile) {<!-- -->
// If the folder does not exist or is not a folder, return null
if (Objects.isNull(dirFile) || !dirFile.exists() || dirFile.isFile()){<!-- -->
return null;
}
File[] childrenFiles = dirFile.listFiles();
if (Objects.isNull(childrenFiles) || childrenFiles.length == 0){<!-- -->
return null;
}
List<File> files = new ArrayList<>();
for (File childFile : childrenFiles) {<!-- -->
// If it is a file, add it directly to the result collection
if (childFile.isFile()) {<!-- -->
files.add(childFile);
}
//After uncommenting the following lines of code, you can get the files in all subfolders into the list
// else {<!-- -->
// // If it is a folder, add its internal files to the result set
// List<File> cFiles = getAllFile(childFile);
// if (Objects.isNull(cFiles) || cFiles.isEmpty()) continue;
// files.addAll(cFiles);
// }
}
return files;
}
public static boolean createFilePath(String path){<!-- -->
try {<!-- -->
File filePath = new File(path);
if (!filePath.exists()) {<!-- -->
if(!filePath.mkdirs()){<!-- -->
return false;
}
}
} catch (Exception e) {<!-- -->
log.error("An error occurred when creating the folder on the server",e);
return false;
}
return true;
}
public static boolean deleteFilePath(File file) {<!-- -->
if (file.isDirectory()) {<!-- -->
String[] children = file.list();
if(null != children & amp; & amp; children.length > 0){<!-- -->
File file1 = null;
// Recursively delete subdirectories in the directory
for(String str : children){<!-- -->
file1 = new File(file, str);
log.info(file1.getPath());
deleteFilePath(file1);
}
}
}
return file.delete();
}
}
Two: Generate temporary txt and write data line by line
public static void main(String[] args) {<!-- -->
File file = new File(path, "empty number.txt");
File file1 = new File(path, "active number.txt");
file.createNewFile();
file1.createNewFile();
writeReport(phoneQuery.getMobile(), file.getPath());
writeReport(phoneQuery.getMobile(), file1.getPath());
}
//Write data line by line
public static void writeReport(String content, String filePath) {<!-- -->
BufferedWriter out = null;
try {<!-- -->
//Encoding format can be changed by yourself
out = new BufferedWriter(new OutputStreamWriter(
new FileOutputStream(filePath, true), "UTF-8"));
out.write(content + "\r\\
");
} catch (Exception e) {<!-- -->
e.printStackTrace();
} finally {<!-- -->
try {<!-- -->
out.close();
} catch (IOException e) {<!-- -->
e.printStackTrace();
}
}
}
Three: Compress the generated txt files into a zip package
List<File> fileList = new ArrayList<>();
File file = new File(path, "empty number.txt");
File file1 = new File(path, "active number.txt");
file.createNewFile();
file1.createNewFile();
writeReport(phoneQuery.getMobile(), file.getPath());
writeReport(phoneQuery.getMobile(), file1.getPath());
//Form of output stream When the front-end receives the stream, set the receiving header to application/zip
ZipUtil.zipDateFile(response, fileList, "test.zip", true);
/**
* Download zip package
*/
@GetMapping("/downZip")
@ApiOperationSupport(order = 10)
@ApiOperation(value = "Download zip package", notes = "Download zip package")
public R test(HttpServletResponse response) throws IOException {<!-- -->
phoneService.downLoadZip(response);
return R.success("success");
}
4. Front end
//js tool class
/**
* Download excel
* @param {blob} fileArrayBuffer file stream
* @param {String} filename file name
*/
export const downloadText= (fileArrayBuffer, filename) => {<!-- -->
let data = new Blob([fileArrayBuffer], {<!-- --> type: 'application/zip' });
if (typeof window.chrome !== 'undefined') {<!-- -->
// Chrome
var link = document.createElement('a');
link.href = window.URL.createObjectURL(data);
link.download = filename;
link.click();
} else if (typeof window.navigator.msSaveBlob !== 'undefined') {<!-- -->
//IE
var blob = new Blob([data], {<!-- --> type: 'application/force-download' });
window.navigator.msSaveBlob(blob, filename);
} else {<!-- -->
// Firefox
var file = new File([data], filename, {<!-- --> type: 'application/force-download' });
window.open(URL.createObjectURL(file));
}
};
//methods method:
handleTemplate(row) {<!-- -->
exportBlob(
`phone/downZip`
).then(res => {<!-- -->
downloadText(res.data, 'file package.zip');
});
},