工具类
也可以写在service层里面
public byte[] download(List<String> filepaths, HttpServletResponse response) throws IOException {
byte[] buffer = new byte[1024];
// 创建一个新的 byte 数组输出流,它具有指定大小的缓冲区容量
ByteArrayOutputStream baos = new ByteArrayOutputStream();
//创建一个新的缓冲输出流,以将数据写入指定的底层输出流
BufferedOutputStream fos = new BufferedOutputStream(baos);
ZipOutputStream zos = new ZipOutputStream(fos);
for (String filepath:filepaths) {
//获取各个文件的数据流
// Get the file name
int a = filepath.lastIndexOf("/");
String str = filepath.substring(a+1);
String filename = str;
URL url = new URL(filepath);
URLConnection connection = url.openConnection();
connection.setConnectTimeout(5*1000);
InputStream stream = connection.getInputStream();
//压缩文件内的文件名称
zos.putNextEntry(new ZipEntry(filename));
int length;
while ((length = stream.read(buffer)) > 0) {
//将文件读入压缩文件内
zos.write(buffer, 0, length);
}
zos.closeEntry();
stream.close();
}
zos.close();
fos.flush();
ByteArrayOutputStream _os = new ByteArrayOutputStream();
InputStream is = new ByteArrayInputStream(baos.toByteArray());
byte[] buffer1 = new byte[1024 * 5];
int len = 0;
while ((len = is.read(buffer1)) > 0) {
_os.write(buffer1, 0, len);
}
_os.flush();
return _os.toByteArray();
}
controller层调用
@GetMapping(value = "/downLoad")
public AjaxResult downLoad(@RequestParam(value = "titles",required = false) List<String> titles , HttpServletResponse response) throws IOException{
//创建需要下载的文件路径的集合
List<String> filePaths = declareHistoryService.selectDownLoad(titles);
//遍历获取fastdfs上的文件的完整url路径
List<String> list = new ArrayList<>();
for (String filePath : filePaths) {
if (null != filePath){
list.add(filePrefix + filePath);}
}
if (list.size() != 0){
byte[] data = historyService.download(list, response);
genCode(response,data);
return AjaxResult.success("下载成功");
}else {
return AjaxResult.error("没有对应的pdf文件可供下载");
}
}
生成下载文件
private void genCode(HttpServletResponse response, byte[] data) throws IOException {
response.reset();
response.addHeader("Access-Control-Allow-Origin", "*");
response.addHeader("Access-Control-Expose-Headers", "Content-Disposition");
response.setHeader("Content-Disposition", "attachment; filename=\"declare.zip\"");
response.addHeader("Content-Length", "" + data.length);
response.setContentType("application/octet-stream; charset=UTF-8");
IOUtils.write(data, response.getOutputStream());
}