Java 获取fastDFS文件导出zip压缩文件
1、获取fastDFS文件byte[]
/**
* 导出压缩包
* @param vo
* @param response
*/
public void downloadFileZip(DownloadFileVo vo, HttpServletResponse response) {
List<Map<String,String>> files = new ArrayList<>();
if(null != vo.getFileVos() && vo.getFileVos().size()>0){
for(DownloadFileVo fileVo:vo.getFileVos()){
String substring=fileVo.getLocationUrl();
if(substring.startsWith("group1")){
substring = substring.substring(7);
byte[] bytes = fastFileStorageClient.downloadFile("group1", substring, new DownloadByteArray ());
Map<String,String> maps = new HashMap<>();
maps.put("fileName",fileVo.getName());
String encoded = Base64.getEncoder().encodeToString(bytes);
maps.put("file",encoded);
files.add(maps);
}
}
ZIPFileUtils.toFileZip(files,vo.getFileName(),response);
}
}
2、通过byte[] 生成文件流并压缩导出
/**
* 字节转FileInputStream
*
* @param bytes
* @return
*/
public static FileInputStream byteToFile(byte[] bytes, String fileName) {
File file = new File(fileName);
FileInputStream fileInputStream = null;
try {
OutputStream output = new FileOutputStream(file);
BufferedOutputStream bufferedOutput = new BufferedOutputStream(output);
bufferedOutput.write(bytes);
fileInputStream = new FileInputStream(file);
file.deleteOnExit();
return fileInputStream;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return fileInputStream;
}
/**
* 压缩成ZIP 方法
* @param srcFiles 需要压缩的文件列表
* @param out 压缩文件输出流
* @throws RuntimeException 压缩失败会抛出运行时异常
*/
public static void toFileZip(List<Map<String,String>> srcFiles,String fileName,HttpServletResponse response)throws RuntimeException {
long start = System.currentTimeMillis();
ZipOutputStream zos = null ;
try {
response.reset();
//response.setContentType("applicatoin/octet-stream");
response.setContentType("application/zip");
//设置头信息 Content-Disposition为属性名 附件形式打开下载文件 指定名称 为 设定的fileName
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
response.addHeader( "Access-Control-Allow-Origin", "*" ); //可以访问此域资源的域。*为所有
ServletOutputStream outResponse = response.getOutputStream();
zos = new ZipOutputStream(outResponse);
for (Map<String,String> map : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(map.get("fileName")));
int len;
FileInputStream in = byteToFile(Base64.getDecoder().decode(map.get("file")), map.get("fileName"));
while ((len = in.read(buf)) != -1){
zos.write(buf, 0, len);
}
zos.closeEntry();
in.close();
}
long end = System.currentTimeMillis();
System.out.println("压缩完成,耗时:" + (end - start) +" ms");
outResponse.flush();
outResponse.close();
} catch (Exception e) {
throw new RuntimeException("zip error from ZipUtils",e);
}finally{
if(zos != null){
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}