服务端
@GetMapping(value = "/download")
public void download(HttpServletRequest request, HttpServletResponse response) {
//文件名以时间戳作为前缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filePrefix = sdf.format(new Date());
String downloadName = "教师聘书" + filePrefix + ".zip";
//将文件进行打包下载
try( OutputStream out = response.getOutputStream()) {
//接收压缩包字节
byte[] data = teachersJobOffersService.download(response);
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
下载方法
@Override
public byte[] download(HttpServletResponse response) {
List<TeachersJobOffers> teachersJobOffersList = list();
try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(outputStream)) {
for (TeachersJobOffers teacher : teachersJobOffersList) {
String dept = teacher.getDepartment() +"/";
String path = teacher.getDepartment() + "/" + teacher.getMajor();
//一级目录创建 可能重复异常
try{
zos.putNextEntry(new ZipEntry(dept));
}catch (Exception e){
}
//二级目录创建 可能重复异常
try{
zos.putNextEntry(new ZipEntry(path));
}catch (Exception e){
}
String fileName = teacher.getClassName() + ".png";
ImageDownload.downloadToZipEntry(zos,teacher.getCertUrl(), path, fileName);
}
zos.closeEntry();
zos.close();
return outputStream.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
下载方法封装
/**
*
* @param zos zip输出流
* @param urlString 文件输入流
* @param directory 文件路径
* @param filename 文件名
* @throws IOException
*/
public static void downloadToZipEntry(ZipOutputStream zos,
String urlString,
String directory,
String filename) throws IOException {
//jdk 1.7 新特性自动关闭
try (InputStream in = getURL(urlString);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
//创建缓冲区
byte[] buff = new byte[1024];
int n;
// 开始读取
while ((n = in.read(buff)) >= 0) {
outputStream.write(buff, 0, n);
}
ZipEntry entry = new ZipEntry(directory + "/" + filename);
entry.setSize(outputStream.toByteArray().length);
zos.putNextEntry(entry);
zos.write(outputStream.toByteArray());
System.out.println(filename);
System.out.println(outputStream.size());
} catch (Exception e) {
e.printStackTrace();
}
}
public static InputStream getURL(String urlString) throws Exception {
URL url = null;
try {
url = new URL(urlString);
} catch (MalformedURLException e) {
e.printStackTrace();
}
//超时重试5次
int N =5;
for (int i = 0; i < N; i++) {
try{
return url.openStream();
} catch (IOException e) {
continue;
}
}
throw new Exception("Failed to download after attepmts");
}
方法二 创建临时文件并压缩
服务端
@GetMapping(value = "/download")
public void download(HttpServletRequest request, HttpServletResponse response) {
teachersJobOffersService.download(response);
// return Result.OK("证书下载成功!");
}
server
@Override
public void download(HttpServletResponse response) {
List<TeachersJobOffers> teachersJobOffersList = list();
String prefix = "教师聘书";
try {
//临时目录创建
Path tempDirWithPrefix = Files.createTempDirectory(prefix);
for (TeachersJobOffers teacher : teachersJobOffersList) {
//路径拼接
Path paths = Paths.get(tempDirWithPrefix.toFile().getAbsolutePath(),teacher.getDepartment(),teacher.getMajor());
String path = paths.toFile().getAbsolutePath();
String fileName = teacher.getClassName() + ".png";
ImageDownload.download(teacher.getCertUrl(), path, fileName);
}
//第二个参数为:要压缩文件的地址
FileZipUtil.exportZip(response, tempDirWithPrefix.toFile().getAbsolutePath(), "教师聘书");
} catch (IOException e) {
e.printStackTrace();
}
}
下载方法
/**
* 文件下载到指定路径
*
* @param urlString 链接
* @param savePath 保存路径
* @param filename 文件名
* @throws Exception
*/
public static void download(String urlString, String savePath, String filename) throws IOException {
// 构造URL
URL url = new URL(urlString);
// 打开连接
URLConnection con = url.openConnection();
//设置请求超时为20s
con.setConnectTimeout(20 * 1000);
//文件路径不存在 则创建
File sf = new File(savePath);
if (!sf.exists()) {
sf.mkdirs();
}
//jdk 1.7 新特性自动关闭
try (InputStream in = con.getInputStream();
OutputStream out = new FileOutputStream(sf.getPath() + "\\" + filename)) {
//创建缓冲区
byte[] buff = new byte[1024];
int n;
// 开始读取
while ((n = in.read(buff)) >= 0) {
out.write(buff, 0, n);
}
} catch (Exception e) {
e.printStackTrace();
}
}
压缩方法
package org.jeecg.common.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
/**
* @author: Haiming Yu
* @createDate:2022/8/16
* @description:
*/
public class FileZipUtil {
private static void handlerFile(ZipOutputStream zip, File file, String dir) throws Exception {
//如果当前的是文件夹,则进行进一步处理
if (file.isDirectory()) {
//得到文件列表信息
File[] fileArray = file.listFiles();
if (fileArray == null) {
return;
}
//将文件夹添加到下一级打包目录
zip.putNextEntry(new ZipEntry(dir + "/"));
dir = dir.length() == 0 ? "" : dir + "/";
//递归将文件夹中的文件打包
for (File f : fileArray) {
handlerFile(zip, f, dir + f.getName());
}
} else {
//当前的是文件,打包处理
//文件输入流
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
ZipEntry entry = new ZipEntry(dir);
zip.putNextEntry(entry);
zip.write(FileUtils.readFileToByteArray(file));
IOUtils.closeQuietly(bis);
zip.flush();
zip.closeEntry();
}
}
private static byte[] createZip(String sourceFilePath) throws Exception {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
ZipOutputStream zip = new ZipOutputStream(outputStream);
//将目标文件打包成zip导出
File file = new File(sourceFilePath);
handlerFile(zip, file, "");
IOUtils.closeQuietly(zip);
return outputStream.toByteArray();
}
/**
* 文件下载地址
* @param response
* @param sourceFilePath
* @param fileName
*/
public static void exportZip(HttpServletResponse response, String sourceFilePath,String fileName) {
//文件名以时间戳作为前缀
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String filePrefix = sdf.format(new Date());
String downloadName = fileName + filePrefix + ".zip";
//将文件进行打包下载
try( OutputStream out = response.getOutputStream()) {
//接收压缩包字节
byte[] data = createZip(sourceFilePath);
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Expose-Headers", "*");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + downloadName);
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream;charset=UTF-8");
IOUtils.write(data, out);
out.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
}
以上就是全部代码 有建议意见可以留言